117

How do I stop and start setInterval?

Suppose I have a textarea. I want to stop setInterval on focus and restart setInterval on blur (with jQuery).

wonea
  • 4,783
  • 17
  • 86
  • 139
testkhan
  • 1,769
  • 4
  • 14
  • 12
  • You have an example in: [enter link description here][1] [1]: http://stackoverflow.com/questions/7483525/pausing-setinterval-when-page-browser-is-out-of-focus – jMiguel LA Mar 14 '12 at 15:47
  • 12
    It only takes one mouse click to accept an answer. It helps others too to see a correct answer amongst many answers. CLICK – Onimusha Feb 04 '13 at 12:50

4 Answers4

190

You have to store the timer id of the interval when you start it, you will use this value later to stop it, using the clearInterval function:

$(function () {
  var timerId = 0;

  $('textarea').focus(function () {
    timerId = setInterval(function () {
      // interval function body
    }, 1000);
  });

  $('textarea').blur(function () {
    clearInterval(timerId);
  });

});
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
  • 6
    I would suggest to add a `if (timerId)clearInteral(timerId)` before `timerId = setInterval` - otherwise, it's not guaranteed that the interval is cleared if focus is called more often than blur. when testing this I saw this situation a few times (on IE10). – Patrick Klug Nov 07 '12 at 06:01
  • @PatrickKlug your right! I needed `if (timerId)clearInteral(timerId)` also – bobbyrne01 Dec 31 '12 at 01:36
29

This is based on CMS's answer. The question asked for the timer to be restarted on the blur and stopped on the focus, so I moved it around a little:

$(function () {
  var timerId = 0;

  $('textarea').focus(function () {
    clearInterval(timerId);
  });

  $('textarea').blur(function () {
    timerId = setInterval(function () {
     //some code here 
    }, 1000);
  });
});
vee
  • 1,247
  • 16
  • 18
SDG
  • 290
  • 3
  • 3
19

Store the return of setInterval in a variable, and use it later to clear the interval.

var timer = null;
$("textarea").blur(function(){
    timer = window.setInterval(function(){ ... whatever ... }, 2000);
}).focus(function(){
    if(timer){
       window.clearInterval(timer);
       timer = null
    }
});
Doug Neiner
  • 65,509
  • 13
  • 109
  • 118
12

setInterval returns an id that you can use to cancel the interval with clearInterval()

Roy Tang
  • 5,643
  • 9
  • 44
  • 74