Using multiple instances of setInterval

女生的网名这么多〃 提交于 2021-02-19 02:33:27

问题


I have a jsFiddle here: http://jsfiddle.net/dztGA/22/

The goal: Essentially, I'm trying to have 2 discrete timers on the same page that can be destroyed and re-created on mouseover/mouseout (pause), or on manual progression (restart).

The problem: What my jsFiddle's single timer will illustrate is that when I click "Stop Timer", my setInterval (stored in variable t) seems to have multiple instances albeit being destroyed with clearInterval(t). This becomes apparent when I click "Restart Timer" and it seems to have 2+ independent timers as illustrated by the quick increment.

A caveat: I have done as much research on SO as I can, but because I'll be having 2 different sliders on the page, I can't use any "clear all timers" methods, so I tried storing each in a variable.

I hope that's clear. Thanks for the view.


回答1:


To fix your current issue: Add clearInterval(window.t) at the onclick function of the reset button.

A method to be able to have multiple timers. This requires a certain structure, though.
Fiddle (6 timers!): http://jsfiddle.net/dztGA/27/

(function(){ //Anonymous function, to not leak variables to the global scope
    var defaultSpeed = 3000; //Used when missing
    var timerSpeed = [500, 1000, 2000, 4000, 8000];

    var intervals = [];
    function increase(i){
        return function(){
            var elem = $("#count"+i);
            elem.text(parseFloat(elem.text()) + 1);
        }
    }
    function clear(i){
        return function(){
            clearInterval(intervals[i]);
        }
    }
    function restart(i){ //Start AND restart
        return function(){
            clear(i)();
            increase(i)();
            intervals[i] = setInterval(increase(i), timerSpeed[i]||defaultSpeed);
        }
    }
    // Manual increment
    $('input[name=increment]').each(function(i){
        $(this).click(function(){
            restart(i)();
            increase(i)();
        });
    });

    // Clear timer on "Clear"
    $('input[name=clear]').each(function(i) {
        $(this).click(clear(i));
    });

    // Restart timer on "Restart"
    $('input[name=reset]').each(function(i) {
        $(this).click(restart(i));

        //Optionally, activate each timer:
        increase(i)();
    });
})();



回答2:


// Clear timer on "Clear"
$('input[name=clear]').click(function() {
    window.clearInterval(t);
});

should be

// Clear timer on "Clear"
$('input[name=clear]').click(function() {
    window.clearInterval(window.t);
});

because this is the input not Window



来源:https://stackoverflow.com/questions/7732009/using-multiple-instances-of-setinterval

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!