1. Posts/

js :: Count down timer in vanilla Javascript

···
Javascript Javascript Timer

In this article I will take you through creating a Timer object in javascript. We will create a javascript object that can be easily used to create multiple timers on a window.

A count down timer can be implemented in JavaScript using setTimeout or setInterval functions along with recursion. You may read this very good article on javascript timers with setTimeout and setInterval. The important difference is setTimeout sets an execution time for a given function and setInterval calls the same function on given interval. Both work on milliseconds range.

A simple example of count down timer using the setTimeout is shown in the jsfiddle below. Run the code from the Result tab.

All this above function does is to update the span content every 1000 milliseconds. As you can see here the setTimeout is applied to the window object. We also use a global variable to determine when to stop the timer. When the countDown() function is called timeout of 1000 milliseconds is set for countDown() function. If you repeatedly click on the start button, timeout of 1000 milliseconds is added at different times.

Now that we understand the simplest timer function, we will go ahead and make improvements to it.

https://jsfiddle.net/deepumohanp/hnt9P/

References
#

  1. https://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/
  2. https://johnresig.com/blog/how-javascript-timers-work/
  3. https://mckoss.com/jscript/object.htm
  4. https://helephant.com/2008/04/26/objects-event-handlers-and-this-in-javascript/