Dejo Dekic
Dejo Dekic

Reputation: 2126

clearInterval doesn't work?

I have some problem with this code, when I click the start button everything is working as expected but when I want to stop animation with clearInterval it doesn’t work, just keeps looping... What I am doing wrong?

 var a = function() { 
     $("div").animate({height:300},"slow");
     $("div").animate({width:300},"slow");
     $("div").animate({height:100},"slow");
     $("div").animate({width:100},"slow");
 }

 $(document).ready(function(){
     $("start").click(function(){

         setInterval(a,1000);
     });

     $("stop").click(function(){
         clearInterval(a);

     });

 });

Upvotes: 9

Views: 23128

Answers (4)

Wasim Karani
Wasim Karani

Reputation: 8886

HTML

<div style="height:310px;width:310px;">
    <div id="div" style="width:100px;height:100px;background-color:#000">
    </div>
</div>

<input type="button" id="start" value="start">
<input type="button" id="stop" value="stop">

JQUERY

var startInterval;

$(document).ready(function(){
     var a = function() { 
         $("#div").animate({height:300},"slow");
         $("#div").animate({width:300},"slow");
         $("#div").animate({height:100},"slow");
         $("#div").animate({width:100},"slow");
     }
     $("#start").click(function(){
         startInterval=setInterval(a, 2500);
     });

     $("#stop").click(function(){
         clearInterval(startInterval);
     });
});

Check this out for reference jsfiddle

Upvotes: 3

ShankarSangoli
ShankarSangoli

Reputation: 69915

You should pass a reference(which you get from setInterval) to clearInterval method to clear it. Try this

var intervalId;
var a = function() { 
    $("div").animate({height:300},"slow");
    $("div").animate({width:300},"slow");
    $("div").animate({height:100},"slow");
    $("div").animate({width:100},"slow");
}

$(document).ready(function(){
    $("#start").click(function(){
        intervalId = setInterval(a,1000);
    });

    $("#stop").click(function(){
        clearInterval(intervalId);
    });

});

Upvotes: 19

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100205

Does this work for you:

var chk =  setInterval(a,1000);
then
clearInterval(chk);

Upvotes: 1

Pointy
Pointy

Reputation: 413996

The "setInterval()" function returns a value. That's what you need to pass to "clearInterval()", not a reference to the handler.

Upvotes: 3

Related Questions