Skip to content Skip to sidebar Skip to footer

Why Doesn't Settimeout Wait To Call A Function?

I want to create a simple game of sorts. I am trying to duplicate a div recursively after a few seconds. After duplicated, it creates the new div with a new unique ID (ID+i). The i

Solution 1:

The argument to setTimeout should be the function pointer to duplicate, not the result of calling the duplicate function.

setTimeout(duplicate(), 2000);

should be

setTimeout(duplicate, 2000);

Also, you might be intending to call the spawnFly function in the timeout, not the duplicate function. The duplicate function would then be called immediately to "spawn" a new fly. Then in 2 seconds, the spawnFly function is called to duplicate another fly and queue spawnFly again. The way you currently have it set up, the it immediately recurs into the spawnFly function, queuing up 15 flies to spawn in 2 seconds and immediately topping out the fly count (x)

Also, you're your increment of i causes an off by 1 error such that you're always trying to assign the value of the next fly to original. You should use pre-increment (++i) instead of post-increment (i++) to get your desired result

All changes applied: https://jsfiddle.net/msrkxq63/3/


Solution 2:

When you call setTimeout in your example, you're passing the result of duplicate(), not the function duplicate itself as the callback. As duplicate does not return anything, setTimeout tries to call the function undefined. You could either call it this way (as an anonymous callback):

setTimeout(function() { duplicate }, 2000)

or simply,

setTimeout(duplicate, 2000)


Solution 3:

If you notice duplicate() in setTimeout(duplicate(),2000);,
it's a function call.
setTimeout 's first parameter is a function. If you pass duplicate(),
it gets evaluated before the wait and looks for the return value and calls that.
Function or not, it waits after the function call and ends up doing nothing after
the wait. So we can say the flow is:
1​. Callback = duplicate()(duplicate is called before wait) = <return value of duplicate> instead of the function duplicate itself.
2. Milliseconds = 2000.
3. Call return value after 2 seconds.
The correct code is:
setTimeout(duplicate,2000)//Note that there are no brackets here


Post a Comment for "Why Doesn't Settimeout Wait To Call A Function?"