Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

History

5 Commits

Repository files navigation

Javascript countdown timer

It converts a javascript timestamp into days, hours, minutes and seconds

Install

Using NPM OR YARN

npm install javascript-timer

OR

yarn add javascript-timer

Usage

You can either include index.js on your html file, or you can simply copy its contents to you main js file

// use a future date (keep it reasonable)consttimestamp=Date.parse("2022-04-11T10:20:30Z");// return a timestamp in msconsttimeObject=calculateTimeUntil(timestamp)/* returns an object with 4 key-value pairs i.e  { days: Number,  hrs: Number, mins: Number,  seconds: Number }*/

You can then use setInterval to populate a countdown elements(s) on your DOM

Example

<scriptsrc = '/js/helpers.js'></script><divclass = 'timer'><divclass = 'timer_value' id = 'days'><spanclass = 'timer_unit'></span><labelclass = 'timer_label'>Days</label></div><spanclass = 'timer_divider'>:</span><divclass = 'timer_value' id = 'hrs'><spanclass = 'timer_unit'></span><labelclass = 'timer_label'>Hours</label></div><spanclass = 'timer_divider'>:</span><divclass = 'timer_value' id = 'mins'><spanclass = 'timer_unit'></span><labelclass = 'timer_label'>Minutes</label></div><spanclass = 'timer_divider'>:</span><divclass = 'timer_value' id = 'seconds'><spanclass = 'timer_unit'></span><labelclass = 'timer_label'>Seconds</label></div></div><script>functionfillUnits(labels,obj){labels.forEach(label=>{letid,num;id=label.id;num=obj[id];num=num<10 ? `0${num}` : num;label.children[0].textContent=num;});}functionpopulateCountDown(timer,num){letlabels,timeTo;timeTo=calculateTimeUntil(num);labels=Array.from(timer.children).filter(function(label){returnlabel.classList.contains('timer_value')});fillUnits(labels,timeTo)}(function(){consttimer=document.currentScript.previousElementSibling;consttimestamp=Date.parse("2022-04-11T10:20:30Z");// return a timestamp in mspopulateCountDown(timer,timestamp);setInterval(function(){populateCountDown(timer,timestamp)},1000);})();</script>

About

A countdown timer that converts javascript timestamp to days, hours, minutes and seconds

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages