【问题标题】:I need to call a function in every 5 second with time duration reset我需要每 5 秒调用一次函数并重置持续时间
【发布时间】:2015-05-28 22:58:12
【问题描述】:

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

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

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

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

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

那么我该如何重新设置时间??

【问题讨论】:

标签: javascript jquery


【解决方案1】:

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

【讨论】:

  • interval = setInterval(imagechanger, 5000); 在您的点击事件中效果更好。将间隔重新分配到interval
  • 这比我的回答简单多了。不错!
【解决方案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();

【讨论】:

    猜你喜欢
    • 2018-05-17
    • 2011-11-03
    • 2022-12-24
    • 2023-03-26
    • 2017-10-28
    • 2011-11-06
    • 2011-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多