Skip to content

Instantly share code, notes, and snippets.

@bearcub3
Forked from adhithyan15/countdown.js
Last active August 1, 2020 18:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bearcub3/991a948a96e6e14eea6ee6571c1e3e18 to your computer and use it in GitHub Desktop.
Save bearcub3/991a948a96e6e14eea6ee6571c1e3e18 to your computer and use it in GitHub Desktop.
A countdown timer in JS with AddTime();
/********************************************************************************************************************
Countdown.js is a simple snippet to add a countdown timer for your app.
I've forked this coding from https://gist.github.com/adhithyan15/4350689 which was
originally a fork of http://jsfiddle.net/HRrYG/.
I've implemented a new feature, addTime(); and modified the coding a little bit to be optimized for usage in my app.
You can see my demo here https://jsfiddle.net/gounshin/as6drbyL/1/
Since the original code that I forked was released under Creative Commons by SA license, so is mine.
********************************************************************************************************************/
function Countdown(seconds) {
this.sec = seconds;
this.mins = seconds > 60? seconds/60 : 0;
tick();
function tick() {
if(this.sec > 60){
this.current_minutes = mins-1;
}
this.sec--;
timeView.textContent = (!this.mins? '00' : this.current_minutes.toString()) + ':' + (this.sec < 10 ? '0' : '') + String(this.sec);
if( this.sec > 0 ) {
// stopTime id is necessary for the function addTime(); if you are just going to use the function countdown();, you can omit it.
stopTime = setTimeout(tick, 1000);
} else {
if(this.mins > 1){
countdown(this.mins-1);
}
}
}
}
function AddTime(seconds){
/* If extra time is added without clearTimeout(stopTime);, the function tick(); inside of the function countdown(); runs twice.
Since the seconds in this parameter is inherited from this.sec in the function countdown(),
the seconds in the timer are decremented every 2 seconds. More accurately, this.sec--; in the function countdown() is invoked twice without clearTimeout(stopTime);.
So the seconds in the timer don't work in the way you would expect. */
clearTimeout(stopTime);
countdown.call(this.sec, seconds);
sec = this.sec + seconds;
}
Countdown(n);
AddTime(n); //where n is the number of seconds required.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment