timer.performWithDelay Question

Hello All,

I’m just messing around with Corona and lua and wanted to make 100 small 15x15 boxes appear randomly on the screen, however all appearing a few seconds apart. Currently, they appear all at once and I was wondering if you could point out what is wrong with my code. 

display.setDefault("anchorX", 0) display.setDefault("anchorY", 0) local function spawnRects() i = 1 while i \< 100 do local x = math.random(1, 305) local y = math.random(1, 480) timer.performWithDelay(5000, display.newRect(x, y, 15, 15)) print("hello") i = i + 1 end end spawnRects()

Thanks!

EDIT** Figured it out. Thank you anyways!

For anyone searching for this problem, it’s helpful to post your solution.

In this case, the problem is that the while loop runs very quickly and creates 100 timers that will trigger 5 seconds later.  And in 5 seconds 100 timers fire near instantaneously.  Your phone/tablet runs at millions of instructions per second, so that for loop probably completely finishes  in well under a millisecond.  

I would have solved it by setting an iteration value for the timer,  

timer.performWithDelay(5000, display.newRect(x, y, 15, 15), 100)

And I’m surprised this worked at all.  The timer.performWithDelay function takes an address to a function, the the results of a function call.  This should have been written more like:

timer.performWithDelay(5000, function() display.newRect(x, y, 15, 15); end, 100)

Rob

For anyone searching for this problem, it’s helpful to post your solution.

In this case, the problem is that the while loop runs very quickly and creates 100 timers that will trigger 5 seconds later.  And in 5 seconds 100 timers fire near instantaneously.  Your phone/tablet runs at millions of instructions per second, so that for loop probably completely finishes  in well under a millisecond.  

I would have solved it by setting an iteration value for the timer,  

timer.performWithDelay(5000, display.newRect(x, y, 15, 15), 100)

And I’m surprised this worked at all.  The timer.performWithDelay function takes an address to a function, the the results of a function call.  This should have been written more like:

timer.performWithDelay(5000, function() display.newRect(x, y, 15, 15); end, 100)

Rob