Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop "setInterval" [duplicate]

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

like image 666
testkhan Avatar asked Dec 02 '09 07:12

testkhan


People also ask

How do you stop a setInterval loop?

You need to clearInterval() method to stop the setInterval() method. Note: 1000 ms = 1 second. If you want to execute a function only once Then use the setTimeout() method.

Does setInterval repeat?

Yes, setInterval repeats until you call clearInterval with the interval to stop.


2 Answers

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);   });  }); 
like image 127
Christian C. Salvadó Avatar answered Sep 22 '22 08:09

Christian C. Salvadó


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);   }); }); 
like image 24
SDG Avatar answered Sep 22 '22 08:09

SDG