简体   繁体   中英

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 idea is that it keeps creating divs and the user has to click on them to remove them for as long as they can before it reaches the max (game over).

It won't properly wait to create the divs. I want to create new divs from the existing one every few seconds, but it either creates all 15 as soon as I run it or it only creates 1 and stops there.

JSFIDDLE - https://jsfiddle.net/namelesshonor/msrkxq63/

function spawnFly() {
if(x >= 15){
    alert("YOU LOST\n15 Flys have infested your screen!");
}
else if(x < 15) {   
    x++; // adds another fly to the counter 
    setTimeout(duplicate(), 2000); // spawns a new fly after a few secs
    animateDiv(); // animate the spawned fly
    spawnFly(); // called recursively until fly count is met
}   
};

function duplicate() {
var original = document.getElementById('fly'+i);
var clone = original.cloneNode(true);
clone.id = "fly" + i++;
clone.onclick = swat;
original.parentNode.appendChild(clone);
};

function animateDiv(){
var newq = makeNewPosition();
var oldq = $('.shoo').offset();
var speed = calcSpeed([oldq.top, oldq.left], newq);
$('.shoo').animate({ top: newq[0], left: newq[1] }, speed, function(){
  animateDiv();        
});
};

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/

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)

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 the function call and ends up doing nothing after函数调用等待,什么都不做
the wait. So we can say the flow is:
1​. Callback = duplicate() ( duplicate = <return value of duplicate > instead of the function duplicate itself. = < duplicate返回值> 而不是函数duplicate本身。
2. Milliseconds = 2000 .
3. Call return value after 2 seconds.
The correct code is:
setTimeout(duplicate,2000)//Note that there are no brackets here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM