使用jquery,我如何制作一个可以立即重启并且可以明显倒计时的计时器?

时间:2015-09-18 08:24:15

标签: javascript jquery timer setinterval

Current jsfiddle

主要问题一直在清除,无论我做什么,即使我清除,每次点击似乎也会运行多个计时器

我整夜都在这。 我只是想在点击时重新启动倒数计时器。 我试图让这个人准备5秒钟 然后7秒钟做动作。 因此,它需要从5开始倒计时,然后从7开始倒计时,如果点击它需要在任何时候完全开始。

它比听起来要困难得多。

我使用了

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

但永远无法让它发挥作用。

2 个答案:

答案 0 :(得分:1)

setTimeout()返回一个可用于取消请求的标识符:

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);`

答案 1 :(得分:1)

试试这个:

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/

相关问题