diff --git a/lib/countdown.js b/lib/countdown.js index 1da554f..de38151 100644 --- a/lib/countdown.js +++ b/lib/countdown.js @@ -3,12 +3,23 @@ var root = this; - var Countdown = function(duration, onTick, onComplete) { + var Countdown = function(duration, onTick, onComplete, step) { var secondsLeft = Math.round(duration) + , step = (step > 0) ? Math.round(step) : 1 , tick = function() { if (secondsLeft > 0) { - onTick(secondsLeft); - secondsLeft -= 1; + onTick(secondsLeft); + if (secondsLeft >= step) { + secondsLeft -= step; + } + else { + // Clear the current interval, and start it up with the the remaining seconds left. + clearInterval(interval); + interval = setInterval( + function() { tick.call(this) }, 1000 * secondsLeft, this + ); + secondsLeft = 0; + } } else { clearInterval(interval); onComplete(); @@ -16,9 +27,7 @@ } // Setting the interval, by call tick and passing through this via a self-calling function wrap. , interval = setInterval( - (function(self){ - return function() { tick.call(self); }; - })(this), 1000 + function() { tick.call(this) }, 1000 * step, this ); // First tick. diff --git a/test/test.js b/test/test.js index 78cac06..725ef39 100644 --- a/test/test.js +++ b/test/test.js @@ -33,6 +33,49 @@ describe("countdown.js", function() { assert(tickFunction.callCount == 5); }); + it("executes onTick while countdown is running with user specified step interval", function() { + new Countdown(5, tickFunction, callbackFunction, 2); + assert(tickFunction.callCount == 1); + clock.tick(1000); + assert(tickFunction.callCount == 1); + clock.tick(1000); + assert(tickFunction.callCount == 2); + clock.tick(1000); + assert(tickFunction.callCount == 2); + clock.tick(1000); + assert(tickFunction.callCount == 3); + clock.tick(1000); + assert(tickFunction.callCount == 3); + }); + + it("defaults to 1 second ticks with invalid step parameter", function() { + new Countdown(2, tickFunction, callbackFunction, -1); + assert(tickFunction.callCount == 1); + clock.tick(1000); + assert(tickFunction.callCount == 2); + clock.tick(1000); + new Countdown(2, tickFunction, callbackFunction, []); + assert(tickFunction.callCount == 3); + clock.tick(1000); + assert(tickFunction.callCount == 4); + clock.tick(1000); + new Countdown(2, tickFunction, callbackFunction, {}); + assert(tickFunction.callCount == 5); + clock.tick(1000); + assert(tickFunction.callCount == 6); + clock.tick(1000); + new Countdown(2, tickFunction, callbackFunction, 'invalid'); + assert(tickFunction.callCount == 7); + clock.tick(1000); + assert(tickFunction.callCount == 8); + clock.tick(1000); + new Countdown(2, tickFunction, callbackFunction, true); + assert(tickFunction.callCount == 9); + clock.tick(1000); + assert(tickFunction.callCount == 10); + clock.tick(1000); + }); + it("executes onComplete", function() { new Countdown(5, tickFunction, callbackFunction); clock.tick(4000);