9

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.

2
  • it's not foo() that is being running unlimited, it runs only once. It's the Interval that runs unlimited. To stops a function you can use return; to stop an interval, tou should use clearInterval. See Scott's answer below Commented Aug 10, 2018 at 20:02
  • "just many lines of code that get executed and I want to stop it from executing after a specific event." - Exiting out of a function like this is done simply with return, but this is a totally different case than an interval. Commented Aug 10, 2018 at 20:02

2 Answers 2

18

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>

Sign up to request clarification or add additional context in comments.

2 Comments

Lets say I'm looping through 1 to 1000 and I want to stop it by another external function which is triggered by the button eg <button type="button" id="stop">Stop</button>
@RahulAhire Please read my answer carefully. It is not possible to stop a running function. What you could do is, instead of a loop, use a setInterval() timer, which causes an asynchronous callback function to run repeatedly, but when it runs, it can check a higher scoped variable which contains a counter that increases each time the timer function runs (the timer function increases it). When the counter reaches 1000, the callback function can call clearInterval() on itself - - causing the repeating function to no longer run. Then, your stop button could do the same thing.
0

For that use return; in the place you want to kill the process

3 Comments

As Scott Marcus answered above, a simple return/break wont stop the interval. A clearInterval is needed.
Let me upload my full code, then you can check it @Michael
No problem, I made the same mistake (:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.