How can I interrupt execution of a JavaScript method? The method is scheduled using the "setTimeout" function in JavaScript, I need to interrupt that method execution(not by calling the "clearTimeout" function because it cannot interrupt a method execution during its execution but can cancel before it already started to executing, after started executing the method "clearTimeout" does not interrupt method execution) I want to interrupt when a particular event occured and take control of flow, What is the JavaScript way to do it?
+2
A:
Don't use setTimeout but setInterval and you'll be able to cancel execution with
clearInterval({your interval});
SleepyCod
2010-10-13 05:03:13
You can also call `clearInterval()` with an interval returned by `setTimeout()` -- https://developer.mozilla.org/en/DOM/window.setTimeout
Jason Hall
2010-10-13 05:08:25
This is no different from the `setTimeout`/`clearTimeout` relationship, so if one doesn't solve the problem, neither will the other. The only thing different about `setInterval` is its call will recur, whereas `setTimeout` will not. --heh, just saw the other comment come in right above mine, sorry for sort of double-posting. But I believe that comment means `clearTimeout` where it says `clearInterval` as well.
Ken
2010-10-13 05:08:51
You answer is not useful for this question. You should delete it.
Alin Purcaru
2010-10-24 19:05:38
+1
A:
Hi,
If your method is synchronous you can't. If it's running asynchronous operations you should use a flag that each operation checks before starting.
Also as SleepyCod said you could use setInterval/clearInterval, but you can do this only if your method needs to do the same thing at certain time periods.
Alin Purcaru
2010-10-13 05:06:26
Actually my method will be on execution when I need to interrupt it, its not before starting execution the method!
buddhi
2010-10-13 05:26:05