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* */
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>
JS let interval = 100let t, durationlet el = document.querySelector(".duration")// Run this function for each intervalfunction handlerFunction(start) {duration = Math.floor((Date.now() - start) / 1000)el.innerText = duration}// Set the Timerfunction startTimer() {let startTime = Date.now()t = setInterval(handlerFunction, interval, startTime)console.log("starting...")}// Stop the Timerfunction 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 cleanupclearInterval(t)}
Result
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>
JS // Query all the container for each hour, minute, and secondlet 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 formatfunction formatDuration(dur) {let h = Math.floor(dur / 3600)let m = Math.floor((dur % 3600) / 60)let s = (dur % 3600) % 60hoursContainer.innerText = hminutesContainer.innerText = msecondsContainer.innerText = s}// Modify the handlerFunction to run formatDuration and pass the duration value as parameterfunction handlerFunction(start) {duration = Math.floor((Date.now() - start) / 1000)formatDuration(duration)}
Result
Bonus: using React and React Hooks
I’ll add this later 😜
Okay, that’s all. Now you got yourself a timer using setInterval