Search code examples
javascriptmethodsexecutioninterrupt

JavaScript method execution interruption


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?


Solution

  • 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.