JavaScript Timers are used to execute code after a specific amount of time or repeatedly after a fixed interval. Timers allow developers to control the timing of program execution and create dynamic behaviour in web applications.
Modern websites use timers for many features such as animations, countdowns, automatic updates, notifications, slideshows, clocks, and delayed actions.
JavaScript provides built-in timer functions that allow developers to schedule tasks without blocking the execution of other code.
A timer is a JavaScript mechanism that allows a function or piece of code to execute after a specified time period.
Timers work with the browser's timing system and execute tasks asynchronously. This means JavaScript can continue running other code while waiting for the timer to complete.
console.log("Start");
setTimeout(function()
{
console.log("After 3 Seconds");
},3000);
console.log("End");
Start End After 3 Seconds
The timer runs after the specified delay while the remaining code continues executing.
Timers help developers create interactive and time-based features in websites.
JavaScript mainly provides two types of timers:
| Timer Function | Description |
|---|---|
| setTimeout() | Executes a function once after a specified delay. |
| setInterval() | Executes a function repeatedly after a fixed time interval. |
The setTimeout() function is used to execute a function once after a specified amount of time.
It is commonly used for delayed messages, animations, notifications, and loading effects.
setTimeout(function, milliseconds);
| Parameter | Description |
|---|---|
| function | The function that will execute after the delay. |
| milliseconds | Time delay in milliseconds. |
1000 milliseconds = 1 second
setTimeout(function()
{
document.write("Welcome to CSE Gyan");
},3000);
Welcome to CSE Gyan
Modern JavaScript allows arrow functions inside timer methods.
setTimeout(() =>
{
console.log("JavaScript Timer");
},2000);
Values can be passed to functions executed by timers.
function message(name)
{
console.log("Hello " + name);
}
setTimeout(message,2000,"Student");
Hello Student
The clearTimeout() function is used to cancel a timer created by setTimeout().
When a timeout is cancelled, the scheduled function will not execute.
clearTimeout(timerID);
let timer =
setTimeout(function()
{
console.log("Hello JavaScript");
},5000);
clearTimeout(timer);
In this example, the timer is cancelled before execution, so the message will not appear.
The setInterval() function is used to execute a function repeatedly after a fixed amount of time. Unlike setTimeout(), which runs only once, setInterval() continues executing the code until it is stopped manually.
It is commonly used for clocks, countdown systems, live updates, animations, and applications that require repeated execution.
setInterval(function, milliseconds);
| Parameter | Description |
|---|---|
| function | The function that will execute repeatedly. |
| milliseconds | The time interval between executions. |
1000 milliseconds represents 1 second.
setInterval(function()
{
console.log("JavaScript Timer Running");
},2000);
JavaScript Timer Running JavaScript Timer Running JavaScript Timer Running ...
The message is displayed repeatedly after every 2 seconds.
A counter is one of the simplest examples of using repeated execution.
let count = 1;
setInterval(function()
{
console.log(count);
count++;
},1000);
1 2 3 4 5 ...
The clearInterval() function is used to stop a timer created using setInterval().
Without clearInterval(), the interval function continues running continuously.
clearInterval(intervalID);
let number = 1;
let timer =
setInterval(function()
{
console.log(number);
number++;
},1000);
setTimeout(function()
{
clearInterval(timer);
console.log("Timer Stopped");
},5000);
1 2 3 4 Timer Stopped
After 5 seconds, the interval is stopped using clearInterval().
| setTimeout() | setInterval() |
|---|---|
| Executes code only once. | Executes code repeatedly. |
| Used for delayed actions. | Used for repeated tasks. |
| Stopped using clearTimeout(). | Stopped using clearInterval(). |
| Runs after specified delay. | Runs after every fixed interval. |
| Suitable for one-time events. | Suitable for continuous updates. |
Digital clocks are common examples of timer usage. The current time is updated every second using setInterval().
function showTime()
{
let date =
new Date();
let time =
date.toLocaleTimeString();
document.getElementById("clock")
.innerHTML=time;
}
setInterval(showTime,1000);
Countdown timers are used in exams, online offers, events, and competitions.
let seconds = 10;
let countdown =
setInterval(function()
{
console.log(seconds);
seconds--;
if(seconds < 0)
{
clearInterval(countdown);
console.log("Time Over");
}
},1000);
10 9 8 7 ... Time Over
A stopwatch measures elapsed time. It uses setInterval() to increase the time continuously.
let seconds = 0;
function startWatch()
{
setInterval(function()
{
seconds++;
console.log(seconds);
},1000);
}
startWatch();
Timers are often controlled using buttons such as Start, Stop, Pause, and Resume.
let timer;
function start()
{
timer =
setInterval(function()
{
console.log("Running");
},1000);
}
function stop()
{
clearInterval(timer);
}
Timers commonly use anonymous functions because the function is required only for a specific task.
setTimeout(function()
{
alert("Welcome User");
},2000);
Arrow functions provide a shorter syntax for writing timer functions.
setInterval(() =>
{
console.log("Updating Data");
},3000);
Every timer function returns a unique ID. This ID is used to control and stop the timer.
let id =
setTimeout(function()
{
console.log("Hello");
},2000);
console.log(id);
The returned ID can be passed to clearTimeout() or clearInterval().
JavaScript timers are not limited to simple delays and repeated execution. Advanced timer concepts help developers create interactive applications, animations, automatic updates, and real-time features.
Understanding how timers work internally improves the ability to build efficient and responsive web applications.
A nested timer means using one timer function inside another timer function. It is useful when different tasks need to execute at different time intervals.
setTimeout(function()
{
console.log("First Task");
setTimeout(function()
{
console.log("Second Task");
},2000);
},3000);
First Task After 2 Seconds Second Task
JavaScript timers are commonly combined with DOM manipulation to update webpage content automatically.
Examples include changing messages, updating counters, creating effects, and refreshing information.
let message =
document.getElementById("msg");
setTimeout(function()
{
message.innerHTML =
"Welcome to CSE Gyan";
},3000);
Timers can modify CSS properties after a specific delay to create visual effects.
let box =
document.getElementById("box");
setTimeout(function()
{
box.style.background =
"blue";
},2000);
JavaScript timers can create basic animations by changing element positions repeatedly.
let position = 0;
let animation =
setInterval(function()
{
position++;
document
.getElementById("box")
.style.left =
position+"px";
if(position==300)
{
clearInterval(animation);
}
},10);
Countdown timers are widely used for exams, offers, events, and online competitions.
let time = 60;
let timer =
setInterval(function()
{
document.getElementById("count")
.innerHTML=time;
time--;
if(time < 0)
{
clearInterval(timer);
document.getElementById("count")
.innerHTML="Time Finished";
}
},1000);
Interactive applications often require users to control timers manually.
let interval;
function startTimer()
{
interval =
setInterval(function()
{
console.log("Timer Running");
},1000);
}
function stopTimer()
{
clearInterval(interval);
}
JavaScript timers do not guarantee exact execution time. They provide the minimum delay after which the function can execute.
The browser executes timer callbacks when the JavaScript engine becomes available.
setTimeout(function()
{
console.log("Timer Completed");
},1000);
The function may execute slightly after 1 second depending on browser activity and running tasks.
JavaScript uses an event loop mechanism to manage asynchronous operations such as timers.
Applications may contain multiple timers. Each timer should have its own ID for proper control.
let timer1 =
setInterval(function()
{
console.log("Timer One");
},1000);
let timer2 =
setInterval(function()
{
console.log("Timer Two");
},2000);
clearInterval(timer1);
clearInterval(timer2);
JavaScript timers are used in many professional applications.
JavaScript Timers provide a powerful way to control time-based operations in web applications. The main timer functions include setTimeout(), setInterval(), clearTimeout(), and clearInterval().
Timers are essential for creating countdowns, clocks, animations, automatic updates, notifications, and interactive user experiences.
A strong understanding of JavaScript timers helps developers build modern and responsive websites with better control over asynchronous tasks.