Skip to content

How to stop a function when it’s called?

I’m building a program that either counts down or up and I’ve got it working however I like to press count-up in the middle of count down or vice versa and I like the counter to stop and count up or vice versa. how do I achieve that? thanks a lot for your help 🙂

function myFunctionUp() {
    var Timer = setInterval(function () {
        i++;
        document.getElementById("mydata").textContent = i;
        if (i >= 21)
            clearInterval(Timer);
            if (i == 21){
                document.getElementById("mydata").textContent = "Boom-up!";
            }
    }, 1000);

}
function myFunctionDown() {
    
    var Timer = setInterval(function () {
        i--;
        document.getElementById("mydata").textContent = i;
        if (i <= 0)
            clearInterval(Timer);
            if (i == 0){
                document.getElementById("mydata").textContent = "Boom-down";
            }
            
    }, 1000);
}

Answer

Use a variable to keep track of the way to count. When a button is clicked, invert the value of the variable :

let countDown = 10;
let increment = -1;

function count() {
  countDown += increment;
  document.getElementById('container').innerText = countDown;
  setTimeout(() => count(), 1000);
}

document.getElementById('btn').addEventListener('click', function () {
  increment = -increment;
});
count();

Working stackblitz here

You typically never “take control” on the execution of another method. When you want to do that, the logic must be inverted. The function itself must ask if it should continue.

With an example : let’s take a function which works in an infinite loop, that you want to be able to stop on demand. In some languages, you could run some code in a thread and interrupt the thread on demand. But even if it is possible, it is generally a bad idea to stop some code at the middle of its execution.

A better way of doing that is to create a “should Continue ?” piece of code at the end of the iteration. It could read a variable or call a method etc. When you want to stop the iteration, you just have to set this variable and you know that the infinite loop will stop graciously at the end of the current iteration