Stop Javascript Function execution from another Function

后端 未结 3 1684
生来不讨喜
生来不讨喜 2021-02-14 05:14

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:44

    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.

提交回复
热议问题