Dan
Dan

Reputation: 2174

Unable to clear interval

I want to terminate the interval created with setInterval if the count goes to 3. I tried the code below but it is not calling the alert inside the if block. Why? Is my comparison not correct or is something else wrong?

 $(window).load(function() {
     var timerId = 1;
     timerId = window.setInterval(function() { 
        timerId = timerId + 1; 
        if(timerId == '3') { 
            alert(timerId);  
            clearInterval(timerId);
         }  
     }, 2000); 
 });

Upvotes: 0

Views: 101

Answers (3)

adeneo
adeneo

Reputation: 318222

Try not using the same variable for everything

$(window).load(function() {
     var timerNum = 1,
         timerId  = window.setInterval(function(){ 
             timerNum++; 
             if( timerNum == 3 ){
                 clearInterval(timerId);
             }  
         }, 2000);  
});

You can't use the same variable for the count and the interval, the count is something you update yourself adding 1 every time the callback in the interval executes, while the setInterval function returns a unique ID that can later be passed to clearInterval to clear that specific interval, and by overwriting that ID with your number the unique ID is lost, and the interval can no longer be cleared.

Upvotes: 7

Pranav C Balan
Pranav C Balan

Reputation: 115232

You are using same variable for storing an integer value and unique interval ID return by window.setInterval. So use different variables , that may fix your problem

$(window).load(function() {
     var timerId =1;
     var intId = window.setInterval(function(){ 
     timerId=timerId+1; 
     if(timerId=='3'){ alert(timerId);  clearInterval(intId);}  
}, 2000);  });

Upvotes: 1

Leth0_
Leth0_

Reputation: 534

$(window).load(function() {
     var timerId =1;
     timerCount = window.setInterval(function(){ 
     timerId=timerId+1; 
     if(timerId=='3'){ alert(timerId);  clearInterval(timerCount);}  
}, 2000);  });

You have two variables with the same name, change one of the variables names to avoid them 'clashing'.

Upvotes: 3

Related Questions