Sep 15, 20191 min read

Create Timer with Javascript, React, and React Hooks

Few days ago I started building a time tracker project and I just realized that I don’t really know how to make timer with Javascript. So, as for documentation of my learning process, here how I did my timer with Javascript.

The main pieces for the timer is setInterval, it is repeatedly calls a function or executes a code snippet, with a fixed time delay between each call and it is a global function available on the window object and also worker.

JS
setInterval(handlerFunction, interval, param1, param2, ...)
/**
* handlerFunction(required): function to execute for every interval
* interval(required) : Duration in miliseconds on how often to execute the handlerFunction
* param(optional) : Additional parameter, will available as parameter on the handler function
* */

  setInterval(handlerFunction, interval, param1, param2, ...)

  /**
   * handlerFunction(required): function to execute for every interval
   * interval(required) : Duration in miliseconds on how often to execute the handlerFunction
   * param(optional) : Additional parameter, will available as parameter on the handler function
   * */

Let’s Start the Code

HTML
<span>Timer</span>
<h3><span class="duration">0</span> seconds</h3>
<button onClick="startTimer()">Start</button>
<button onClick="stopTimer()">Stop</button>
<span>Timer</span>
<h3><span class="duration">0</span> seconds</h3>

<button onClick="startTimer()">Start</button>
<button onClick="stopTimer()">Stop</button>
JS
let interval = 100
let t, duration
let el = document.querySelector(".duration")
// Run this function for each interval
function handlerFunction(start) {
duration = Math.floor((Date.now() - start) / 1000)
el.innerText = duration
}
// Set the Timer
function startTimer() {
let startTime = Date.now()
t = setInterval(handlerFunction, interval, startTime)
console.log("starting...")
}
// Stop the Timer
function stopTimer() {
// Cleanup Timer
// Run this when stopping or when you're done with the timer to avoid memory leak
// The setInterval will keep running if you are not doing cleanup
clearInterval(t)
}
let interval = 100
let t, duration
let el = document.querySelector(".duration")

// Run this function for each interval
function handlerFunction(start) {
  duration = Math.floor((Date.now() - start) / 1000)
  el.innerText = duration
}

// Set the Timer
function startTimer() {
  let startTime = Date.now()
  t = setInterval(handlerFunction, interval, startTime)
  console.log("starting...")
}

// Stop the Timer
function stopTimer() {
  // Cleanup Timer
  // Run this when stopping or when you're done with the timer to avoid memory leak
  // The setInterval will keep running if you are not doing cleanup
  clearInterval(t)
}

Result

Timer0 seconds
See Demo on Codepen »

Format Duration to Hours, Minutes, and Seconds

To do this, we need to add markup for the hour, minutes, and seconds to the HTML

HTML
<h3>
<span><span class="hours">0</span>h</span> :
<span><span class="minutes">0</span>m</span> :
<span><span class="seconds">0</span>s</span>
</h3>
<h3>
  <span><span class="hours">0</span>h</span> :
  <span><span class="minutes">0</span>m</span> :
  <span><span class="seconds">0</span>s</span>
</h3>
JS
// Query all the container for each hour, minute, and second
let hoursContainer = document.querySelector(".hours")
let minutesContainer = document.querySelector(".minutes")
let secondsContainer = document.querySelector(".seconds")
// Add function to convert the duration value into H:M:S format
function formatDuration(dur) {
let h = Math.floor(dur / 3600)
let m = Math.floor((dur % 3600) / 60)
let s = (dur % 3600) % 60
hoursContainer.innerText = h
minutesContainer.innerText = m
secondsContainer.innerText = s
}
// Modify the handlerFunction to run formatDuration and pass the duration value as parameter
function handlerFunction(start) {
duration = Math.floor((Date.now() - start) / 1000)
formatDuration(duration)
}
// Query all the container for each hour, minute, and second
let hoursContainer = document.querySelector(".hours")
let minutesContainer = document.querySelector(".minutes")
let secondsContainer = document.querySelector(".seconds")

// Add function to convert the duration value into H:M:S format
function formatDuration(dur) {
  let h = Math.floor(dur / 3600)
  let m = Math.floor((dur % 3600) / 60)
  let s = (dur % 3600) % 60
  hoursContainer.innerText = h
  minutesContainer.innerText = m
  secondsContainer.innerText = s
}

// Modify the handlerFunction to run formatDuration and pass the duration value as parameter
function handlerFunction(start) {
  duration = Math.floor((Date.now() - start) / 1000)
  formatDuration(duration)
}

Result

Timer0h : 0m : 0s
See Demo on Codepen »

Bonus: using React and React Hooks

I’ll add this later 😜

Okay, that’s all. Now you got yourself a timer using setInterval