ClearInterval not working?

I have some problems with this code, when I press the start button, everything works as expected, but when I want to stop the animation using clearInterval , it does not work, it just continues the loop ... What am I 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); }); }); 
+6
source share
4 answers

You must pass the link (which you get from setInterval ) to the clearInterval method to clear it. try it

 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); }); }); 
+13
source

The setInterval () function returns a value. This is what you need to pass "clearInterval ()", not a reference to a handler.

+2
source

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 jsfiddle reference

+2
source

This works for you:

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

Source: https://habr.com/ru/post/901809/


All Articles