How to stop "setInterval"

JavascriptJquerySetinterval

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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

});

Solution 2 - Javascript

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

Solution 3 - Javascript

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

Solution 4 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontestkhanView Question on Stackoverflow
Solution 1 - JavascriptChristian C. SalvadóView Answer on Stackoverflow
Solution 2 - JavascriptSDGView Answer on Stackoverflow
Solution 3 - JavascriptDoug NeinerView Answer on Stackoverflow
Solution 4 - JavascriptRoy TangView Answer on Stackoverflow