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
2 Answers
Reset to default 8waitHandler.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.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745232088a4617723.html
评论列表(0条)