Javascript is one of the most powerful languages which powers the front end as well as communicates with the back end too. If you have some working knowledge of js then you may notice that timer events are required for many purposes. Mainly javascript doesn’t provide any timer events. So this task is accomplished with a method called setTimeout. In this post, I will explain how to use it as a javascript timer with a bunch of examples.

How to use a javascript timer?

First of all, the setTimeout method is the best way to execute something after a given time. This method can accept 2 parameters and It has the following syntax.

setTimeout(function name,time in miliseconds)

Let's check it out with an example. Suppose you want to display a hello world alert after 3 seconds. Then the code for that will be as follows.

setTimeout(‘alert(” Hello World “)’, 3000)

I haven’t added the markup or something. So if you want to test it you can simply open your browser console and test the above code there. As a result, you will get something like below.


javascript settimeout

So now we know how to use the setTimeout method now let's do some Lil bit moderate things.

Stopwatch with javascript

We will create a stopwatch with 3 buttons by pure vanilla javascript. If you guys want to check the final result of this guide you can watch it here. So first create a project directory and create 3 files one HTML,one CSS, and one js file. Now, let's add markup for stopwatch. I assume that you guys know the proper HTML structure. So after the body tag add the given code.


<div class="wrapper">
	<div class="timer">
		<div class="hour">
			<p id="h"></p>
		</div>
		<div class="minute">
			<p id="m"></p>
		</div>
		<div class="second">
			<p id="s"></p>
		</div>
	</div>
	<button id="start">Start</button>
	<button id="pause">Pause</button>
	<button id="stop">Stop</button>
</div>

So in the above code, you can I have just added all the buttons and timer box inside a wrapper. So that’s all you need in your HTML file. Now lets head over to CSS and add some styles.


* {
	padding:0;
	margin:0;
	box-sizing:border-box;
}
html,body {
	font-family:"Century Gothic";
	background:#5f8eed;
	text-align:center;
	padding:20px;
	color:#fff;
}
.wrapper {
	border:4px solid #111;
	display:block;
	height:220px;
	width:220px;
	margin:20px auto;
	padding:20px;
	border-radius:50%;
	background:rgba(17,17,17,0.7);
}
.timer {
	display:flex;
	padding:5px 2px;
	margin:20px 10px;
	background:#202020;
	color:#fff;
}
.timer div {
	flex:1;
	font-size:18px;
	padding:5px 2px;
	border-left:1px solid #ddd;
	border-right:1px solid #ddd;
}
button {
	border:0;
	font-size:14px;
	padding:8px 10px;
	background:rgba(217,217,217,0.6);
	cursor:pointer;
	transition:0.3s all linear;
}
button:hover {
	background:rgba(217,217,217,1);
}

In the above CSS code I have just added some simple CSS rules. While it's not necessary to write the exact same styles you can customize it in any way you like. So finally our CSS file is ready so let's move to the final step.

Use of javascript timer event

First off all I will break the code into smaller parts and explain as its the best way possible to understand. So open your js file and add the following code


let startBtn = document.getElementById('start'),
	stopBtn = document.getElementById('stop'),
	pauseBtn = document.getElementById('pause'),
	hour = document.getElementById('h'),
	minute = document.getElementById('m'),
	second = document.getElementById('s');

Before we manipulate an element always store it into a variable. I have used let to declare a variable but you can use var also. I have selected elements by their id value and it’s done using the getElementById method. Ok, let's move further and add initial values to our stopwatch.


document.addEventListener('DOMContentLoaded', function() {
	hour.innerText = 0 + " h";
	minute.innerText = 0 + " m";
	second.innerText = 0 + " s";
});

In the above code, I have created an event listener that will fire once the page is loaded. So the above code makes sure the initial values of our stopwatch is set. Now its time to bind an event on our buttons.


startBtn.addEventListener('click',start);
stopBtn.addEventListener('click',stop);
pauseBtn.addEventListener('click',pause);

var stop = false;
var pause = false;

So you can see the different events are attached to different buttons. In addition to these 2 Boolean variables are also initialized. Now we have to write code for the methods start, stop and pause. Let’s start with stop and pause.


function stop() {
	stop = true;
	second.innerText = 0 + " s";
	minute.innerText = 0 + " m";
	hour.innerText = 0 + " h";
}

function pause() {
	pause = true;
}

So you can see if the pause is pressed then set pause to true. If the stop is pressed then set all values to 0 and turn stop to true. Finally, it’s time to add code for the start method. It will be a bit lengthy so a separate block will look better.

Stopwatch in action

I have added this project to JSFiddle also. So now you can check it live.

<iframe width="100%" height="300" src="//jsfiddle.net/subham97/gsf08vn7/embedded/" allowfullscreen="allowfullscreen" allowpaymentrequest frameborder="0"></iframe>

First of all i will add comment lines to make sure the logic is much cleaner. Ok so now before the stop and pause method add the following lines.


function start() {
	// extract the integer value from times
	let h = parseInt(hour.innerText),
		m = parseInt(minute.innerText),
		s = parseInt(second.innerText);
	// increment seconds
	s = s + 1;
	// if its 60 seconds then set it to 0 and increse minute
	if(s == 60) {
		s = 0;
		// if its 60 minutes then set it to 0 and increse hour
		if(m == 60) {
			m = 0;
			h = h + 1;
			hour.innerText = h + " h";
		}
		m = m + 1;
		minute.innerText = m + " m";
	}
	// if stop is not pressed
	if(!stop) {
		// if pause is not pressed
		if(!pause) {
			// increase time
			second.innerText = s + " s";
			setTimeout(start,1000);
		} else {
			// toggle pause
			pause = !pause;
		}
	} else {
		// toggle stop
		stop = !stop;
	}
}function start() {
	// extract the integer value from times
	let h = parseInt(hour.innerText),
		m = parseInt(minute.innerText),
		s = parseInt(second.innerText);
	// increment seconds
	s = s + 1;
	// if its 60 seconds then set it to 0 and increse minute
	if(s == 60) {
		s = 0;
		// if its 60 minutes then set it to 0 and increse hour
		if(m == 60) {
			m = 0;
			h = h + 1;
			hour.innerText = h + " h";
		}
		m = m + 1;
		minute.innerText = m + " m";
	}
	// if stop is not pressed
	if(!stop) {
		// if pause is not pressed
		if(!pause) {
			// increase time
			second.innerText = s + " s";
			setTimeout(start,1000);
		} else {
			// toggle pause
			pause = !pause;
		}
	} else {
		// toggle stop
		stop = !stop;
	}
}

So now everything is done. Now save the files open your browser and run it. It will look something like below.

Finally, we have completed the javascript timer guide. I hope javascript timer events are clear to you now. If you have any queries regarding this you can leave a comment. Anyway if you guys like this post then share with friends and let them also learn about this.