Stop Javascript Function execution from another Function

后端 未结 3 1390
野的像风
野的像风 2021-02-14 04:41

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         


        
3条回答
  •  一生所求
    2021-02-14 05:41

    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.

提交回复
热议问题