最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript: Multiple clearTimeout in array - Stack Overflow

programmeradmin0浏览0评论

I have an array with timeout id's. What is the most elegant way to clear all of them at once? Is there a more efficient style than this?

waitHandler[1] = setTimeout('doSomethingA()', 2000);
waitHandler[2] = setTimeout('doSomethingB()', 2000);
...

for (var i=1; i < waitHandler.length; i++) {
    clearTimeout[i];
}

I have an array with timeout id's. What is the most elegant way to clear all of them at once? Is there a more efficient style than this?

waitHandler[1] = setTimeout('doSomethingA()', 2000);
waitHandler[2] = setTimeout('doSomethingB()', 2000);
...

for (var i=1; i < waitHandler.length; i++) {
    clearTimeout[i];
}
Share Improve this question asked Nov 18, 2014 at 9:56 RobbitRobbit 1,5872 gold badges9 silver badges10 bronze badges 4
  • Don't write code in strings. var t = 2000; var ids = [setTimeout(doSomethingA, t), ...]; – 1983 Commented Nov 18, 2014 at 10:33
  • Okay, but what if I need to consign params? – Robbit Commented Nov 18, 2014 at 11:42
  • Then use anonymous functions: setTimeout(function(){doSomethingA(param)}) – Scimonster Commented Nov 18, 2014 at 11:44
  • Ah, is this more performant or just a better coding style? – Robbit Commented Nov 18, 2014 at 12:58
Add a ment  | 

2 Answers 2

Reset to default 8
waitHandler.forEach(clearTimeout);

I think what you mean to do is this:

for (var i=1; i < waitHandler.length; i++) {
    clearTimeout(waitHandler[i]);
}

Your old syntax wouldn't work.


And this is the only way to do it without plugins.

发布评论

评论列表(0)

  1. 暂无评论