如何停止/清除间隔

时间:2014-02-06 13:37:48

标签: javascript jquery

我正在尝试停止/清除间隔但我收到错误。

以下代码:

   function play(){
      function sequencePlayMode() {
         var arg1;//some arguments
         var arg2;//some arguments
         changeBG(arg1,arg2);//here is function that changes the background
      }

     var time = 5000;
     var timer = setInterval(sequencePlayMode, time);//this starts the interval and animation

    }


    function stop(){
       var stopPlay  = clearInterval(sequencePlayMode);//here i'm getting error "sequencePlayMode is not defined"
    }


    $("#startAnimation").click(function(){
            play();
    });

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

有人可以帮我这个吗?

1 个答案:

答案 0 :(得分:5)

您需要使用存储函数的变量而不是您调用它的函数。您还需要使该变量可供其他函数访问。

(function () {  

   var timer;  //define timer outside of function so play and stop can both use it
   function play(){
      function sequencePlayMode() {
         var arg1;//some arguments
         var arg2;//some arguments
         changeBG(arg1,arg2);//here is function that changes the background
      }

     var time = 5000;
     timer = setInterval(sequencePlayMode, time);//this starts the interval and animation

    }


    function stop(){
       var stopPlay  = clearInterval(timer);
    }


    $("#startAnimation").click(function(){
            play();
    });

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

})();