How do I stop a window.setInterval in javascript?

You can't pause an interval, but you can stop it and restart it.

var timer = setInterval(xx,tt);

// then some time later
clearInterval(timer);

You just have to capture the return value from setInterval() and call clearInterval() on it when you want to stop it.

The other way to do a repeat that you can stop repeating at any time is to do a repeated setTimeout() and then clearTimeout() to stop the next timer or just don't kick off the next setTimeout().


If you are using jQuery I would recommend the plugin jQuery Timer

var timer = $.timer(function() {
  alert('This message was sent by a timer.');
}, 2000, true);

Then you can easily pause the timer:

timer.pause();

And also resume it:

timer.play();

There's no built-in "pause" function, but you can stop it, and then start a new interval with the same function.

First, you need to capture the id returned by the call to setInterval:

let intervalId = window.setInterval(...);

Then when you want to stop it, call

 window.clearInterval(intervalId);

In your case I'd suggest defining setScreen by itself, and not inside of the call to setInterval. This way you can just use intervalId = window.setInterval(setScreen, 2000) when you want to resume it.


It's easier to do this by using window.setTimeout() instead of window.setInterval(). The following is adapted from my answer here.

Live demo: http://jsfiddle.net/timdown/Hkzex/

Code:

function RecurringTimer(callback, delay) {
    var timerId, start, remaining = delay;

    this.pause = function() {
        window.clearTimeout(timerId);
        remaining -= new Date() - start;
    };

    var resume = function() {
        start = new Date();
        timerId = window.setTimeout(function() {
            remaining = delay;
            resume();
            callback();
        }, remaining);
    };

    this.resume = resume;

    this.resume();
}