Creating a Timer in pure JavaScript can be surprisingly easy! A Timer is an implementation of a clock that counts up from zero, usually measuring the number of seconds since the start of a countdown. In this blog post, I am going to show you how to create a basic Timer in JavaScript, and then how to refine it with a few bells and whistles.
The first step is to create a basic timer, which can be done with just a couple of lines of code. Start by creating a variable to keep track of the time:
let time = 0;
Next, add a function that will increment the time by one each time it is called:
function incrementTime() { time++; }
Now, you need a way to call the incrementTime() function at regular intervals. To do this, we can use a setInterval() method, which will call a given function at a specified interval. Call the setInterval() method on the incrementTime() function, passing in 1000 milliseconds (1 second):
setInterval(incrementTime, 1000);
Finally, you need a way to display the time. Write a function that logs the time to the console:
function displayTime() { console.log(time); }
You can now call the displayTime() function whenever you want to see the current value of the timer.
This simple Timer is good enough to start with, but it can be improved in a couple of ways. First of all, the time is displayed in the number of seconds since the timer began. To make this a bit more user-friendly, you can convert the seconds into minutes and seconds, using something like this:
function displayTime() { let minutes = Math.floor(time / 60); let seconds = time % 60; if (seconds < 10) { seconds = '0' + seconds; } console.log(minutes + ':' + seconds); }
Another improvement is to add a way to control the timer. This can be done with two additional functions – one to start the timer, and one to stop it:
let intervalId; function startTimer() { intervalId = setInterval(incrementTime, 1000); } function stopTimer() { clearTimeout(intervalId); }
Now you have a fully functioning Timer written in pure JavaScript. You can start and stop the timer, and the time is displayed in a format that users can understand.