Is there a way to clear all JavaScript timers at once?

后端 未结 4 1789
夕颜
夕颜 2020-12-28 15:30

Im building an automatic refreshing comment section for my website using jQuery .load. So I am using a javascript \'setTimeout\' timer to check for new comments.

But

4条回答
  •  佛祖请我去吃肉
    2020-12-28 16:29

    Warning: My code bellow is problematic, mainly because the requirement is itself is problematic. I wonder why would you want to clear all timers any way. This makes your code breaking any plugin the uses the timers. Which is much more common than you may think, unless of course you're debugging or having fun, then it doesn't matter.


    If you must:

    This is one of the worst possible solutions. However it reveals a potential security vulnerability in JavaScript itself. But since it just works (clears ALL of the timers) I thought it would be cool to share it:

    var maxId = setTimeout(function(){}, 0);
    
    for(var i=0; i < maxId; i+=1) { 
        clearTimeout(i);
    }
    

提交回复
热议问题