clearInterval不起作用?

Dej*_*kic 6 jquery

我有这个代码的一些问题,当我点击开始按钮时,一切都按预期工作但当我想停止动画时clearInterval它不起作用,只是保持循环...我做错了什么?

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

     });

 });
Run Code Online (Sandbox Code Playgroud)

Sha*_*oli 13

您应该将引用(您从中获取setInterval)传递给clearInterval方法以清除它.试试这个

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

});
Run Code Online (Sandbox Code Playgroud)