简体   繁体   English

为什么这个setTimeout代码会建立而不是终止?

[英]Why does this setTimeout code build up and not terminate?

If you click the body of the html once and wait until the ball is offscreen its fine. 如果您单击html的正文一次,然后等到球不在屏幕上就好了。 However if you clicked 2+ times you'll notice the ball moving faster. 但是如果你点击2次以上,你会注意到球的移动速度更快。 When you click the body again to make the ball come back it is still faster then it should be. 当您再次单击身体以使球返回时,它仍然比应该的要快。 Why? 为什么? http://jsfiddle.net/44nwt/10/ http://jsfiddle.net/44nwt/10/

-edit- in firefox on my page (i havent tried on jsfiddle) i notice the move func is called repeatably even after the ball has left screen and been removed. 在页面上的firefox中编辑(我还没有在jsfiddle上尝试过),我注意到即使在球离开屏幕并被移走后,移动函数也被重复调用。 Why isnt it existing? 为什么不存在?

if (left > parseInt($('.ballwrapper').css('width'))) {
    //alert('removed');
    $('.ball').remove();
    return;
}

If left is undefined (ie, the ball has been already removed) then the condition is false and the scheduling will be done repeatedly 如果left未定义(即,球已经被移除)则条件为假并且将重复进行调度

This works (http://jsfiddle.net/44nwt/11/) 这有效(http://jsfiddle.net/44nwt/11/)

there were two issues: 有两个问题:

#1 every click creates another instance of ball and ballwrapper, and adds them into the body. #1每次单击都会创建另一个ball和ballwrapper实例,并将它们添加到主体中。 It's only necessary to create the instance if it doesn't already exist. 如果实例尚不存在,则只需创建实例。 So that would look something like this: 所以这看起来像这样:

 $('body').click(function() {
    var wrapper = $('.ballwrapper');
    if( wrapper.length == 0 ) {
        $('body').append('<div class="ballwrapper"><img class="ball" src="http://michaelreid.typepad.com/.a/6a00e54edabd838833011168a00f09970c-800wi"/></div>');
    }
    MoveCode();
});

#2 You need a gate at the beginning of your MoveCode function, to prevent the "extra" cycles (the ones that get started by each extra click) from proceeding once the ball/ballwrapper has been removed. #2你需要在MoveCode函数的开头有一个门,以防止在移除球/球包装器后继续进行“额外”循环(每次额外点击开始的循环)。

function MoveCode() {
    var wrapper = $('.ballwrapper');
    if( wrapper.length == 0 ) return;

    var l = $('.ball').css("left");
    var left = parseInt(l);
    if (left > parseInt(wrapper.css('width'))) {
        //alert('removed');
        wrapper.remove();
        return;
    }

    $('.ball').css("left", (left + 60) + "px");
    setTimeout(MoveCode, 160);
}

Also note... I changed it to remove the ballwrapper, rather than removing just the ball. 还要注意......我改变了它以移除球形包装,而不是仅仅移除球。 Otherwise, if you run it all the way through over and over again, you'll accumulate old, unused ballwrappers in the background. 否则,如果一遍又一遍地运行它,则会在背景中堆积旧的,未使用的包装纸。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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