How do I stop a window.setInterval in javascript?

Solution 1:

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.

Solution 2:

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();

Solution 3:

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();
}

Solution 4:

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().

Solution 5:

Do not re-declare anything

Simply add a class that tells the interval not to do anything. For example: on hover.

var i = 0;
window.setInterval(function() { //declare new function
  if(!$('#counter').hasClass('pauseInterval')) { //only run if it hasn't got this class 'pauseInterval'
    $('#showCount').html(i++); //just for explaining and showing
  }
}, 500);

$('#counter').hover(function() { //mouse enter
    $(this).addClass('pauseInterval');
    $('#counting').text('Stopped counting...');
  },function() { //mouse leave
    $(this).removeClass('pauseInterval');
    $('#counting').text('Counting...');
  }
);
<!-- you'll need jQuery for this. If you really want a vanilla version, ask -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div id="counter"><span id="counting">Counting...</span> | <span id="showCount"></span></div>