Large lag when making next level segment (multi thread help)

Godot Version

4.1.2

Question

Hello, I’m making an endless platforming game. However, there’s lots of lag when it makes the next section of a level. I’m pretty sure it’s because it’s trying to do a lot in one frame, but it doesn’t need to be in one frame as the player can’t even see it yet. I initially tried to fix it by making the next section generate in multiple frames, which definitely did help as it was actually playable, but still very noticeable.

After researching, I think I need to use multi threading, could someone help me with that? I’ve tried for a few days now trying to get it to work. Essentially I need the pictured code and the functions it uses to uh not try so hard doing it all in one frame because it doesn’t need to.

Thank you so much!

This is the main function that makes the next section of the level. It calls other functions that do use set cell (I think that means I have to use call_deffered?) and moves the location of 2 other sprites.
image