Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clearInterval doesn't work?

Tags:

jquery

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

     });

 });
like image 425
Dejo Dekic Avatar asked Nov 18 '11 14:11

Dejo Dekic


3 Answers

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

});
like image 109
ShankarSangoli Avatar answered Nov 15 '22 11:11

ShankarSangoli


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

like image 31
Pointy Avatar answered Nov 15 '22 11:11

Pointy


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

like image 3
Wazy Avatar answered Nov 15 '22 10:11

Wazy