2014-02-06 89 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