2014-02-06 71 views
-1

我试图停止/清除间隔,但我收到错误。下面如何停止/清除间隔

代码:

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

有人可以帮助我吗?

+0

clearInterval(timer);试试这个 – laaposto

+0

可能的重复[停止JavaScript中的setInterval调用](http://stackoverflow.com/questions/109086/stop-setinterval-call-in-javascript) – plalx

回答

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

})(); 
+0

+1使用适当的关闭 – Candide

+0

@epascarello - 当然。 .silly me..how来我错过了!非常感谢! :)) – medzi