Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop Javascript Function execution from another Function

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 runs for few time  };
MainFuntion();

<button onclick="(Here I want some thing to stop MainFunction())">Stop the running script </button>

so basic idea is to return a function from another function

like image 631
Ramiz Ansari Avatar asked Mar 19 '15 16:03

Ramiz Ansari


1 Answers

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:

  1. 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);
      }
    }
    
  2. Use web workers. They allow running code in parallel, but have some restrictions and are not supported by all browsers.

like image 79
Radu Balaban Avatar answered Sep 17 '22 20:09

Radu Balaban