Countdown/ Count Up Timer With JavaScript

Before we start you need to know some stuff like:

1- Executing Code at Regular Intervals:

you can use the setInterval() function to execute a function or specified piece of code repeatedly at fixed time intervals. Its basic syntax is setInterval(function, milliseconds).

This function also accepts two parameters: a function, which is the function to execute, and interval, which is the number of milliseconds representing the amount of time to wait before executing the function (1 second = 1000 milliseconds).

2- Executing Code After a Delay:

The setTimeout() function is used to execute a function or specified piece of code just once after a certain period of time. Its basic syntax is setTimeout(function, milliseconds).

3- Stopping Code Execution:

After referring an interval or a timeout to a variable you can use that variable to disable or clear the timer and stop the execution of code beforehand. Clearing a timer can be done using two functions: clearTimeout() and clearInterval().



A) Count Up Timer:

Here is some basic HTML:


JavaScript code:


As you can see we've used "setInterval" method which is gonna execute that same inner code every 999ms (1s-1ms).

What that inner code does is:
  • increment the "sec" variable every 999ms.
  • if sec was different than 59s then take the sec value and put it the span with the id "sec".
  • else (which is if sec==59s) then sec=0 and min++, then take the "min" variable and put its value on the span with the id "min".

Live Example:

00:00


B) Countdown Timer:

What the code below does is:
  • decrement the "sec" variable every 999ms.
  • if sec was different than 0s then take the sec value and put it the span with the id "sec".
  • else (which is if sec==0s) then sec=59 and min--, then take the "min" variable and put its value on the span with the id "min".


Live Example:

00:00


If  we want to start the timer after a delay lets say 5s, all we need to do is add setTimeout(timer(),5000),
timer() is a function that contain the code above.

If we want tot stop the timer: clearInterval(Interval_ID);

Post a Comment

0 Comments