开发者

clearTimeout on multiple references

I have a set of complex setTimeout() calls that trigger some jQuery animations. I would like to be able to clear them all without knowing their various refs.

This code will not work - but should illustrate what I'm trying to do...

window.ref = [];
func开发者_JS百科tion doAnimation(i) {
    $('div').each(function(index) {
        window.ref.push(setTimeout('foo(index,i)',index*1000));
        window.ref.push(setTimeout('bar(index,i)',index*2000));
    });
}

Then clear them with

clearTimeout(window.ref);


I know this already has an accepted answer, but just because those timeout ids are worthless once you have cleared them, I would have cleared them by saying:

if (window.ref) while(window.ref.length > 0) clearTimeout(window.ref.pop());


thats not correct you should do like this:

window.ref = [];
function doAnimation(i) {
    $('div').each(function(index) {
        window.ref.push(setTimeout('foo(index,i)',index*1000));
        window.ref.push(setTimeout('bar(index,i)',index*2000));
    });
}

and then clear like :

for(var i=0;i<window.ref.length;i++){    
    clearTimeout(window.ref[i]);
}


if (window.ref && window.ref.length > 0) for (var i in window.ref) {
   clearTimeout(window.ref[i]);
}

Or do it the jQuery way:

$.each(window.ref, function (index, value) { clearTimeout(value); });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜