Max Meents
Max Meents

Reputation: 81

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

Current jsfiddle

the main problem has been clearing, no matter what I do the interval seems to run multiple timers for each click even though I clear

I've been at it all night. I simply would like to restart a countdown timer on click. I'm trying to give the person 5 seconds to prepare and then 7 seconds to do the action. so, it needs to countdown from 5 then countdown from 7 and at anytime if clicked it needs to start completely over.

Its much harder than it sounds.

I used a combo of

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

but could never get it to work.

Upvotes: 0

Views: 80

Answers (2)

elad.chen
elad.chen

Reputation: 2425

Try this one:

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/

Upvotes: 1

Flub
Flub

Reputation: 26

setTimeout() returns an identifier you can use to cancel the request:

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

Then you can cancel it later, unless it already has been executed:

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

If you need to visualize it you can do something like this:

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

Upvotes: 1

Related Questions