Why doesn't setTimeout wait to call a function?

試著忘記壹切 提交于 2019-12-24 13:25:01

问题


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();        
});
};

回答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/




回答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)



来源:https://stackoverflow.com/questions/32467369/why-doesnt-settimeout-wait-to-call-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!