I have a function that populates a map with little pellets. When I use a single while task.wait() do loop it takes 167 seconds to populate the entire map. However, if I copy and paste that loop 5 times, it only takes 33 seconds. 10 loops? 17 seconds. Obviously, the more loops, the more times the function is run. My question is: Is there a better way to call the same function as often as possible without using a million loops?
The code I am using for this testing is:
local logged = false
local start = os.time()
local loops = 0
repeat
task.spawn(function()
while task.wait() do
local count = Pellets.total
if count < 10000 then
CreatePellet()
else
if not logged then
logged = true
print("took " .. os.time() - start .. " seconds")
end
end
end
end)
loops += 1
task.wait()
until loops == 40
You can make the function call itself recursively n times, task.spawn the function the first time it’s called and no need to do so when calling it again inside itself
A small example to make more sense
local MAX_DEPTH = 10
local function spawnPellets() -- just make it spawn a reasonable amount while staying under ~2 seconds
end
local function handlePelletSpawning(depth: number): nil
if depth == MAX_DEPTH then return end
task.spawn(spawnPellets)
handlePelletSpawning(depth + 1)
end
task.spawn(handlePelletSpawning, 1)
@SubtotalAnt8185’s solution worked best (in my use case, at least) and only took ~1 second to spawn all 10k pellets.
@msix29’s solution also works; however, it required some modification to be used in the way I needed, and in the end, simply wasn’t as effective. However, this solution would likely be helpful if you didn’t need the loop anymore after it completed its initial task.