我需要在每5秒内调用一个函数,并重置持续时间

I need to call a function in every 5 second with time duration reset

本文关键字:函数 一个 持续时间 5秒 调用      更新时间:2023-09-26

am使用下面的jquery每1秒更改一次中的图像

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

自动换碟机工作正常。现在我需要添加下一个按钮。我在下一次单击按钮时调用相同的imagechanger()函数。这也很好

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

但假设在调用第一个更改并等待4秒后,我按下下一个按钮,当我单击按钮时,图像正在更改,但就在下一秒,另一个更改调用也被触发。

那么我该如何重置时间呢??

要重置间隔,需要将其存储到一个变量中,然后在创建新间隔之前对其调用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   
});

我的解决方案是制作一个简单的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();