使用jquery,我怎样才能制作一个可以立即重启并明显倒计时的计时器?

Using jquery, how can I make a timer that can be immediately restarted and counts down visibly?

Current jsfiddle

主要问题是清除,无论我做什么,间隔似乎 运行 每次点击都有多个计时器,即使我清除了

我整晚都在做这件事。 我只是想在点击时重新启动倒数计时器。 我试着给这个人 5 秒的准备时间 然后7秒做动作。 因此,它需要从 5 开始倒计时,然后从 7 开始倒计时,并且在任何时候点击它都需要完全重新开始。

这比听起来要难得多。

我使用了

的组合
clearInterval()
var Interval = setInterval(function(){}, 1000);

但永远无法让它工作。

setTimeout() returns 可用于取消请求的标识符:

var timerId = setTimeout(function() { console.log('Now!'); }, 5000);

那么你可以稍后取消它,除非它已经被执行过:

$('#cancelTimerButton').click(function() {  clearTimeout(timerId); });

如果你需要可视化它,你可以这样做:

var n = 0;
var tick = function() {
    console.log(n % 2 ? 'Tock' : 'Tick');
    timerId = setTimeout(tick, 1000);
    if (++n == 5) {
        clearTimeout(timerId);
    }
};
var timerId = setTimeout(tick, 1000);`

试试这个:

var timer = (function() {
    var timer = null;

    return {
        start: function( timesToRun, callback, interval ) {
            var timesRan = 0
            timer = setInterval( function() {
                if ( timesRan < timesToRun ) {
                    timesRan++
                    callback( timesRan, timesRan === timesToRun )
                } else {
                    clearInterval( timer )
                }
            }, interval || 1000 )

            return this 
        },

        stop: function() {
            clearInterval( timer )

            return this
        }
    }
}())

var cyclesLabel = document.getElementById("t")

// first argument is the amount of times to run the interval
// second argument is a callback to use on each iteration
// the 3rd argument is optional and is the interval time in milliseconds.
timer.start( 7, totalCycles, 1000 )

// Reset example
document.getElementById("btn").addEventListener( "click", function() {
   cyclesLabel.textContent = "0"
   timer.stop().start( 5, totalCycles )
} )

// Just for the sake of the example
function totalCycles( cycles, lastCycle ) {
   cyclesLabel.textContent = cycles

   if ( lastCycle === true ) {
     alert( "This is the last chance to do something" )
   }
}

http://jsfiddle.net/eedny9jn/2/