Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop a function during its execution - JavaScript

Tags:

javascript

How can I stop/terminate a function which is already executed and still running? For example, I have this function:

function foo() {
  setInterval(function() {
    console.log("Foo Executed !");
  }, 3000);
}
foo();

Now, this foo() function will run for unlimited time, when a specific event occurs, let's say a stop button has been clicked, then I want to stop this function.

In my case the function doesn't have setInterval() function. And what if the foo() function don't have the setInterval() method, but just many lines of code that get executed and I want to stop it from executing after a specific event.

like image 853
Nadeem Ahmad Avatar asked Aug 10 '18 19:08

Nadeem Ahmad


People also ask

Does return stop a function JavaScript?

The return statement stops the execution of a function and returns a value.

How do you break a function in TypeScript?

The following example tells you, how to use a break statement in TypeScript. You can use an existing TypeScript file or create a new project using the following steps to create a program that uses the TypeScript break keyword. Open Visual Studio and click on "File" menu -> "New" -> "Project". A window will be opened.


1 Answers

Stopping a running function is a bit different than what you are actually showing for code, which is an asynchronous operation happening outside of the function that initiated it.

Running functions can only be terminated from within the function and that is done with either a return statement or by throwing an exception.

return can be called conditionally so that the function doesn't always exit at the same point. This is often the case with form validation functions - - if something is determined to be invalid, a return is encountered so that the form is not submitted. If everything is valid, the return is skipped and the form is submitted.

Here's a simple example with return:

function foo1(){
  console.log("Foo started...");
  if(prompt("Type 1 to terminate right now or anything else to continue...") == "1"){
    return;  // Function will terminate here if this is encountered
  }
  console.log("Foo ending...");  // This will only be run if something other than 1 was entered
}

foo1();

And, here's an example with throwing an error (not something that is usually done):

function foo(){
  console.log("foo started...");
  
  for(var i = 0; i < 5; i++){
    if(i === 3) { throw "I HATE 3!"; }
    console.log(i);
  }
  console.log("foo ended...");
}

foo();

But, with Timers and Intervals, you'll need to call clearInterval() and/or clearTimeout() to stop them. These are different because, while some function may initiate the timer or interval, the timer runs outside of the JavaScript runtime environment as a WebAPI. For these, we have to send a message to the WebAPI that we want the timer to stop counting.

You say:

Now, this foo() function will run for unlimited time, when a specific event occurs, let's say a stop button has been clicked, then I want to stop this function.

But foo isn't running for an unlimited time. It's run once and then terminates. Then approximately 3 seconds later, the timer calls for the anonymous function you passed to it to be run and then that function terminates and approximately 3 seconds later the anonymous function runs again and then it again terminates and so on. The function isn't running consistently, the interval timer (the WebAPI that calls for the function to be invoked) is.

And what if the foo() function don't have the setInterval() method, but just many lines of code that get executed and I want to stop it from executing after a specific event.

Your question seems to imply that you want to stop a function that is currently executing when another event takes place. This can't really happen in JavaScript since JavaScript is a single-threaded environment. Any event can only be raised and handled after all other code is done processing. So, there really can't ever be a scenario like the one you mention, unless we are talking about asynchronous code. Asynchronous code is code that runs outside of the JavaScript runtime. With that kind of code, you can send a message to the WebAPI that is processing that external code that you would like to cancel/abort that processing and that is what we're doing when we call clearInterval().

See below:

document.getElementById("start").addEventListener("click", startInterval);
document.getElementById("stop").addEventListener("click", stopInterval);

// You'll need a variable to store a reference to the timer
var timer = null;

function startInterval() {
  // Then you initilize the variable
  timer = setInterval(function() {
    console.log("Foo Executed!");
  }, 1500);
}

function stopInterval() {
  // To cancel an interval, pass the timer to clearInterval()
  clearInterval(timer);
}
<button type="button" id="start">Start</button>
<button type="button" id="stop">Stop</button>
like image 133
Scott Marcus Avatar answered Nov 14 '22 23:11

Scott Marcus