19

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

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Ramiz Ansari
  • 524
  • 1
  • 6
  • 16
  • 99% of the time, you don't need to do this so it's likely an [xy problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem/233676#233676). Please explain your use case so a better solution can be provided. Often, generator functions can be a better approach, but it's hard to make a recommendation without context. – ggorlen Aug 04 '22 at 17:21
  • Use asynchronous js and promises. – Oybek Odilov Sep 06 '22 at 16:11

4 Answers4

18

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.

Radu Balaban
  • 421
  • 3
  • 6
  • I was trying to do some thing that isnt possible. Your answer open my mind it helped me quite much. i broke my long code into many functions with if statements so now i can stop them using a variable. thanks man! – Ramiz Ansari Mar 22 '15 at 01:52
5

You can pass an argument, like cancel, whenever you are calling the MainFunction. So, if you want the function to start, you pass in an arguement '0', and if you want it to stop, you can call the function again with an arguement which is not '0', like '1'. Here is a working example:

function MainFunction(cancel) {
var yourcode;
  if (cancel == 0) {
    yourCode = setInterval(function() {
      //Put your code here, this is an example:
      document.getElementById('div').style.color = "red";
    }, 1);
  }
  if (cancel == 1) {
    clearInterval(yourCode);
    document.getElementById('div').style.color = "black";
  }
}
<html>
  <head>
    <title>My website</title>
  </head>
  <body>
    <button id="btn" onclick="MainFunction(0)">Start</button>
    <button onclick="MainFunction(1)">Stop</button>
    <div id="div">This division can change colour</div>
  </body>
</html>
aravk33
  • 469
  • 2
  • 10
  • 18
0

I think you are trying to stop the execution of other function call from a function. if yes then you need to put the called function inside the condition so that you can control the execution.

if my understanding is not correct please elaborate what you want to do , mens why want to stop the execution of the function.

Nirmal Dhara
  • 2,121
  • 18
  • 27
  • sir my long code will execute for some time it will post some data to my server one after another (so it will run for some time). but i want a stop button there which can stop that execution so i wanted something like onclick="stop code". – Ramiz Ansari Mar 21 '15 at 22:15
0

You can use setTimeout and clearTimeout

something.onclick('timeout()')

something.onclik('myStopFunction()')

var myVar;

function timeout() {
  myVar = setTimeout(()=>{MainFuntion(); }, 3000);
}

function myStopFunction() {
  clearTimeout(myVar);
}

For more information check this link https://www.w3schools.com/jsref/met_win_cleartimeout.asp

KevinCK
  • 415
  • 3
  • 10
  • The timeout is until the function is called, so the clearTimeout() will only succeed to STOP the function from being called (if it has not been called yet). Once called however, it will run till completed. – akeem Mar 21 '23 at 18:55