Is there any way to stop the execution of a called function from another function?
I have following code:-
function MainFunction() { //a long code that r
JavaScript is normally single threaded - meaning that while a function is executed in the browser no other code can run at the same time - including event handlers such as onclick
(they will be triggered only after the function is complete). So, in this case you cannot interrupt the execution of a function from code.
There are two workounds:
The long running function could take breaks intentionally, allowing other code to execute.
//set this to true from an event handler to stop the execution
var cancelled = false;
function longRunningFunction() {
if (cancelled) {
return;
}
// do some work, but not all
// save your progress to be able to resume when called again
if (!done) {
// release control, so that handlers can be called, and continue in 10ms
setTimeout(longRunningFunction, 10);
}
}
Use web workers. They allow running code in parallel, but have some restrictions and are not supported by all browsers.