views:

1074

answers:

4

how can i stop and start setInterval on focus and blur.....!! suppose i have a textarea i want to stop setInvterval on textarea focus and restart setInvterval on textarea blur with jquery

+5  A: 

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

});
CMS
I'm going to bed. Otherwise I am going to keep answering the same questions you answer... haha! +1 for a great answer.
Doug Neiner
+2  A: 

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
+1  A: 

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

Roy Tang
but how can i implement this with $.live or $.listen
testkhan
`$.live` does not currently support `focus` and `blur` events.
Doug Neiner
A: 

I think remove window from window.clearInterval dien dan mua ban

tivi online