2015-03-25 59 views
2

正在使用下面的jquery用於改變圖像在每1秒我需要調用一個函數在每5第二,持續時間復位

window.setInterval(function(){ imagechanger(); }, 5000);

作爲自動更換其工作的罰款。現在我需要添加下一個按鈕。我在下一個按鈕單擊時調用相同的imagechanger()函數。這也是工作的罰款

$('body').on('click','#next',function(){ 
    imagechanger();  
}); 

但在調用第一個變化等待4秒鐘後想的話,我按下一個按鈕,當我點擊該按鈕圖像被改變,但很下一秒另一個變化呼叫也引發。

那麼我如何重置時間?

+1

https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearInterval – MLeFevre 2015-03-25 10:17:21

+1

http://stackoverflow.com/questions/18270009/reset-timer設置的間隔 也 http://code-tricks.com/start-stop-and-reset-javascript-setinterval/ – CodeWithCoffee 2015-03-25 10:18:07

+0

重複:http://stackoverflow.com/questions/8126466/javascript-reset- setinterval-back-to-0 – 2015-03-25 10:18:30

回答

5

要重置間隔,您需要將其存儲到變量中,然後在創建新變量之前調用clearInterval。試試這個:

// on load 
var interval = setInterval(imagechanger, 5000); 

$('body').on('click', '#next', function() { 
    clearInterval(interval); // clear current interval 
    imagechanger(); // call instantly 
    interval = setInterval(imagechanger, 5000); // create new interval 
}); 
+0

'interval = setInterval(imagechanger,5000);'在你的點擊事件中更好。要將間隔重新分配給'間隔' – R3tep 2015-03-25 10:23:03

+0

@ R3tep,謝謝你,這是我的一個疏忽。 – 2015-03-25 10:23:33

+0

這比我的回答更簡單和更甜美。太好了! – 2015-03-25 10:34:03

2

我的解決方案是製作一個簡單的Timer對象並讓它處理間隔。

http://jsfiddle.net/fk5cnvc2/

var Timer = function (interval) { 
    var me = this; 
    var timeout = null; 

    me.interval = interval; 

    me.tick = function() {}; 

    me.reset = function() { 
     if (timeout != null) { 
      clearTimeout(timeout); 
     } 
     timeout = setTimeout(function() { 
      me.tick(); 
      timeout = null; 
      me.reset(); 
     }, me.interval); 
    } 

    me.start = function() { 
     me.reset(); 
    } 

    me.stop = function() { 
     clearTimeout(timeout); 
    } 
} 

    function addResult() { 
     $('#results').append("<div>Tick!</div>"); 
    } 

var myTimer = new Timer(5000); 
myTimer.tick = addResult; 

$('#button').on('click', function() { 
    addResult(); 
    myTimer.reset(); 
}); 

myTimer.start(); 
相關問題