How to stop "setInterval"

testkhan picture testkhan · Dec 2, 2009 · Viewed 186.4k times · Source

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

Answer

Christian C. Salvadó picture Christian C. Salvadó · Dec 2, 2009

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

});