- Javascript Basics Tutorial
- Javascript - Home
- JavaScript - Roadmap
- JavaScript - Overview
- JavaScript - Features
- JavaScript - Enabling
- JavaScript - Placement
- JavaScript - Syntax
- JavaScript - Hello World
- JavaScript - Console.log()
- JavaScript - Comments
- JavaScript - Variables
- JavaScript - let Statement
- JavaScript - Constants
- JavaScript - Data Types
- JavaScript - Type Conversions
- JavaScript - Strict Mode
- JavaScript - Reserved Keywords
- JavaScript Operators
- JavaScript - Operators
- JavaScript - Arithmetic Operators
- JavaScript - Comparison Operators
- JavaScript - Logical Operators
- JavaScript - Bitwise Operators
- JavaScript - Assignment Operators
- JavaScript - Conditional Operators
- JavaScript - typeof Operator
- JavaScript - Nullish Coalescing Operator
- JavaScript - Safe Assignment Operator
- JavaScript - Delete Operator
- JavaScript - Comma Operator
- JavaScript - Grouping Operator
- JavaScript - Yield Operator
- JavaScript - Spread Operator
- JavaScript - Exponentiation Operator
- JavaScript - Operator Precedence
- JavaScript Control Flow
- JavaScript - If...Else
- JavaScript - While Loop
- JavaScript - For Loop
- JavaScript - For...in
- Javascript - For...of
- JavaScript - Loop Control
- JavaScript - Break Statement
- JavaScript - Continue Statement
- JavaScript - Switch Case
- JavaScript - User Defined Iterators
- JavaScript Functions
- JavaScript - Functions
- JavaScript - Function Expressions
- JavaScript - Function Parameters
- JavaScript - Default Parameters
- JavaScript - Function() Constructor
- JavaScript - Function Hoisting
- JavaScript - Self-Invoking Functions
- JavaScript - Arrow Functions
- JavaScript - Function Invocation
- JavaScript - Function call()
- JavaScript - Function apply()
- JavaScript - Function bind()
- JavaScript - Closures
- JavaScript - Variable Scope
- JavaScript - Global Variables
- JavaScript - Smart Function Parameters
- JavaScript Objects
- JavaScript - Number
- JavaScript - Boolean
- JavaScript - Strings
- JavaScript - Arrays
- JavaScript - Date
- JavaScript - DataView
- JavaScript - Handler
- JavaScript - Math
- JavaScript - RegExp
- JavaScript - Symbol
- JavaScript - Sets
- JavaScript - WeakSet
- JavaScript - Maps
- JavaScript - WeakMap
- JavaScript - Iterables
- JavaScript - Reflect
- JavaScript - TypedArray
- JavaScript - Template Literals
- JavaScript - Tagged Templates
- Object Oriented JavaScript
- JavaScript - Objects
- JavaScript - Classes
- JavaScript - Object Properties
- JavaScript - Object Methods
- JavaScript - Static Methods
- JavaScript - Display Objects
- JavaScript - Object Accessors
- JavaScript - Object Constructors
- JavaScript - Native Prototypes
- JavaScript - ES5 Object Methods
- JavaScript - Encapsulation
- JavaScript - Inheritance
- JavaScript - Abstraction
- JavaScript - Polymorphism
- JavaScript - Destructuring
- JavaScript - Destructuring Assignment
- JavaScript - Object Destructuring
- JavaScript - Array Destructuring
- JavaScript - Nested Destructuring
- JavaScript - Optional Chaining
- JavaScript - Global Object
- JavaScript - Mixins
- JavaScript - Proxies
- JavaScript Versions
- JavaScript - History
- JavaScript - Versions
- JavaScript - ES5
- JavaScript - ES6
- ECMAScript 2016
- ECMAScript 2017
- ECMAScript 2018
- ECMAScript 2019
- ECMAScript 2020
- ECMAScript 2021
- ECMAScript 2022
- JavaScript Asynchronous
- JavaScript - Asynchronous
- JavaScript - Callback Functions
- JavaScript - Promises
- JavaScript - Async/Await
- JavaScript - Microtasks
- JavaScript - Promisification
- JavaScript - Promises Chaining
- JavaScript - Timing Events
- JavaScript - setTimeout()
- JavaScript - setInterval()
- JavaScript Cookies
- JavaScript - Cookies
- JavaScript - Cookie Attributes
- JavaScript - Deleting Cookies
- JavaScript Browser BOM
- JavaScript - Browser Object Model
- JavaScript - Window Object
- JavaScript - Document Object
- JavaScript - Screen Object
- JavaScript - History Object
- JavaScript - Navigator Object
- JavaScript - Location Object
- JavaScript - Console Object
- JavaScript Web APIs
- JavaScript - Web API
- JavaScript - History API
- JavaScript - Storage API
- JavaScript - Forms API
- JavaScript - Worker API
- JavaScript - Fetch API
- JavaScript - Geolocation API
- JavaScript Events
- JavaScript - Events
- JavaScript - DOM Events
- JavaScript - addEventListener()
- JavaScript - Mouse Events
- JavaScript - Keyboard Events
- JavaScript - Form Events
- JavaScript - Window/Document Events
- JavaScript - Event Delegation
- JavaScript - Event Bubbling
- JavaScript - Event Capturing
- JavaScript - Custom Events
- JavaScript Error Handling
- JavaScript - Error Handling
- JavaScript - try...catch
- JavaScript - Debugging
- JavaScript - Custom Errors
- JavaScript - Extending Errors
- JavaScript Important Keywords
- JavaScript - this Keyword
- JavaScript - void Keyword
- JavaScript - new Keyword
- JavaScript - var Keyword
- JavaScript HTML DOM
- JavaScript - HTML DOM
- JavaScript - DOM Methods & Properties
- JavaScript - DOM Document
- JavaScript - DOM Elements
- JavaScript - DOM Attributes (Attr)
- JavaScript - DOM Forms
- JavaScript - Changing HTML
- JavaScript - Changing CSS
- JavaScript - DOM Animation
- JavaScript - DOM Navigation
- JavaScript - DOM Collections
- JavaScript - DOM NodeList
- JavaScript - DOM DOMTokenList
- JavaScript Advanced Chapters
- JavaScript - Bubble Sort Algorithm
- JavaScript - Circular Reference Error
- JavaScript - Code Testing with Jest
- JavaScript - CORS Handling
- JavaScript - Data Analysis
- JavaScript - Dead Zone
- JavaScript - Design Patterns
- JavaScript - Engine and Runtime
- JavaScript - Execution Context
- JavaScript - Function Composition
- JavaScript - Immutability
- JavaScript - Kaboom.js
- JavaScript - Lexical Scope
- JavaScript - Local Storage
- JavaScript - Memoization
- JavaScript - Minifying JS
- JavaScript - Mutability vs Immutability
- JavaScript - Package Manager
- JavaScript - Parse S-Expressions
- JavaScript - Prototypal Inheritance
- JavaScript - Reactivity
- JavaScript - Require Function
- JavaScript - Selection API
- JavaScript - Session Storage
- JavaScript - SQL CRUD Operations
- JavaScript - Supercharged Sorts
- JavaScript - Temporal Dead Zone
- JavaScript - Throttling
- JavaScript - TRPC Library
- JavaScript - Truthy and Falsy Values
- JavaScript - Upload Files
- JavaScript - Date Comparison
- JavaScript - Recursion
- JavaScript - Data Structures
- JavaScript - Base64 Encoding
- JavaScript - Callback Function
- JavaScript - Current Date/Time
- JavaScript - Date Validation
- JavaScript - Filter Method
- JavaScript - Generating Colors
- JavaScript - HTTP Requests
- JavaScript - Insertion Sort
- JavaScript - Lazy Loading
- JavaScript - Linked List
- JavaScript - Nested Loop
- JavaScript - Null Checking
- JavaScript - Get Current URL
- JavaScript - Graph Algorithms
- JavaScript - Higher Order Functions
- JavaScript - Empty String Check
- JavaScript - Form Handling
- JavaScript - Functional Programming
- JavaScript - Parameters vs Arguments
- JavaScript - Prototype
- JavaScript - Reactive Programming
- JavaScript - Reduce Method
- JavaScript - Rest Operator
- JavaScript - Short Circuiting
- JavaScript - Undefined Check
- JavaScript - Unit Testing
- JavaScript - Validate URL
- JavaScript Miscellaneous
- JavaScript - Ajax
- JavaScript - Async Iteration
- JavaScript - Atomics Objects
- JavaScript - Rest Parameter
- JavaScript - Page Redirect
- JavaScript - Dialog Boxes
- JavaScript - Page Printing
- JavaScript - Validations
- JavaScript - Animation
- JavaScript - Multimedia
- JavaScript - Image Map
- JavaScript - Browsers
- JavaScript - JSON
- JavaScript - Multiline Strings
- JavaScript - Date Formats
- JavaScript - Get Date Methods
- JavaScript - Set Date Methods
- JavaScript - Modules
- JavaScript - Dynamic Imports
- JavaScript - BigInt
- JavaScript - Blob
- JavaScript - Unicode
- JavaScript - Shallow Copy
- JavaScript - Call Stack
- JavaScript - Reference Type
- JavaScript - IndexedDB
- JavaScript - Clickjacking Attack
- JavaScript - Currying
- JavaScript - Graphics
- JavaScript - Canvas
- JavaScript - Debouncing
- JavaScript - Performance
- JavaScript - Style Guide
- JavaScript Useful Resources
- JavaScript - Questions And Answers
- JavaScript - Quick Guide
- JavaScript - Cheatsheet
- JavaScript - Functions
- JavaScript - Resources
- JavaScript - Online Editor
JavaScript - Timer Functions
In JavaScript, timers are a very noteworthy feature. Like the normal watch timer, we can start the timer at a time and execute the function or code in JavaScript after a particular time.
In simple terms, we can use the timer to execute the code after some delay. For example, when you visit some website, it shows the signup box after 3 to 4 minutes of your visit, and that we can achieve using JavaScript. We can set the delay timer to show the signup popup box.
Another good example of the timer in real life is ads inside the application. When you open any application, it starts showing ads after 2 to 3 minutes and changes the ads in the interval of 1 to 2 minutes.So, there are two different functions to set timers in JavaScript, which we will explore in this tutorial.
Why do we need Timer Functions
- Timer functions are useful when you have to execute a piece of code after certain time.
- Also, useful for scheduling task.
- They are also used for repeating certain tasks.
- Timer functions are also used for developing animations and games.
Types of Timer Function
There are two types of timer functions in JavaScript
- setTimeout() - This function is used to execute the code once after a certain time is passed.
- setInterval() - This function is used to execute the code repeatedly after a certain time.
The setTimeout() Function
The setTimeOut() function allows us to execute a code after a particular delay. However, it allows us to define the delay. It executes the code only once after a particular delay.
When the setTimeOut() function executes, it starts the timer, and after the particular delay, it executes the callback function. This function takes two parameters −
- callback -It is a function to execute after a delayed amount of time.
- delay - The delay is the time in the milliseconds to execute the callback function after that time.
Syntax
Users can follow the syntax below to use the setTimeOut() function.
let timeoutId = setTimeout(callback, delay);
The setTimeOut() function returns the unique id, which we can use to kill the timer.
Note: In the above syntax, the callback function also can be an arrow function to execute.
Example
In the example below, when the user clicks on the Start Timer button, it will call the callTimer() function. Users can see that it prints the callTimer function executed first, and after 2000 milliseconds, it prints This function executed after some delay as the setTimeOut() function calls the callback function after 2000 milliseconds.
<html>
<body>
<h2> Using the setTimeOut() function </h2>
<div id = "output"> </div>
<button id = "btn" onclick = "callTimer()"> Start Timer </button>
<script>
let output = document.getElementById("output");
output.innerHTML += "Program execution started </br>";
function callTimer() {
output.innerHTML = "The callTimer function executed <br/>";
setTimeout(callback, 2000);
}
function callback() {
output.innerHTML += "This function executed after some delay.";
}
</script>
</body>
</html>
Press the Start Timer button to see the output.
Output
Following is the output of the above code −
Program execution started The callTimer function executed This function executed after some delay.
The setInterval() Function
The setTimeOut() function executes the callback function only once, but the setInterval() function executes the code after every interval that we have passed as a second parameter of the setInterval() function.
setInterval() takes two parameters:
- callback - It is a function that setInterval() function call after every interval.
- delay - It is the time in milliseconds to call the callback function after every interval.
Syntax
Users can follow the syntax below to use the setInterval() function.
setInterval(callback, interval);
Note: The setInterval() function also returns the unique id like the setTimeout() function, which we can use to stop the timer.
Example
In this example, we have used the setInterval() function to call the callback function after every 1000 milliseconds. Users can observe that when they press the start timer button, the startInterval() function will execute and which will invoke setInterval() function. The setInterval() function call the callback function after every second.
<html>
<body>
<h2> Using the setInterval() function </h2>
<div id = "output"> </div>
<button id = "btn" onclick = "startInterval()"> Start Timer </button>
<script>
let output = document.getElementById("output");
let count = 0;
let TimerId = "";
function startInterval() {
TimerId = setInterval(() => {
output.innerHTML += "count = " + count + "<br/>";
count += 1;
if(count > 50) {
clearInterval(TimerId);
}
}, 1000);
}
</script>
</body>
</html>
Output
Following is the output of the above code
count = 0 count = 1 . . . count = 50
To avoid the infinite loop, we have used the if statement to check if the count is greater than 50 and kill the timer using the clearInterval() function. We will discuss the clearInterval() function in the next section.
Using clearInterval() functions to kill the Timer
After starting the timer, we need to stop that. We can use the clearInterval() function to stop the setInterval() function. The clearInterval() function takes the unique id returned by the setInterval() function and stops the timer.
Parameters:
- TimerId: It is a unique id returned by either the setTimeOut() or setInterval() function.
// To stop the setInterval() function clearInterval(TimerId);
Example for clearInterval function
In the example below, we call the function after every second using the setInterval() timer function. Also, we keep track of the count of how many times the callback function is invoked by the setInterval() function.
In the callback function, we use the if statement to check if the count is greater than three and kill the timer using the clearInterval() function.
<html>
<body>
<h2> Using the <i> clearInterval() </i> function </h2>
<div id = "output"> </div>
<button id = "btn" onclick = "startInterval()"> Start Timer </button>
<script>
let output = document.getElementById("output");
let count = 0;
let TimerId = "";
function startInterval() {
TimerId = setInterval(() => {
output.innerHTML += "count = " + count + "<br/>";
count += 1;
if (count > 3) {
clearInterval(TimerId);
}
}, 1000);
}
</script>
</body>
</html>
Output
Following is the output of the above code
count = 0 count = 1 count = 2 count = 3
In the above output, users can observe that it prints till count = 3, as we had killed the timer when the count became greater than 3.
Using clearTimeout() function to kill the Timer
After starting the timer, we need to stop that. We can use the clearTimeout() function to stop the setTimeOut() function.
Parameters:
- TimerId: It is a unique id returned by either the setTimeOut() or setInterval() function.
// To stop the setTimeOut() function clearTimeout(TimerId);
Example for clearTimeout function
In the example below, we have used the setTimeOut() function to call the callback function after 2000 milliseconds. Also, we have used the clearTimeout() function to kill the timer after 1000 milliseconds.
<html>
<body>
<h2> Using the <i> clearTimeout() </i> function </h2>
<div id = "output"> </div>
<button id = "btn" onclick = "callTimer()"> Start Timer </button>
<script>
let output = document.getElementById("output");
let TimerId = "";
function callTimer() {
output.innerHTML = "The callTimer function executed <br/>";
TimerId = setTimeout(callback, 2000);
setTimeout(() => {
clearTimeout(TimerId);
output.innerHTML += "Timer killed after 1000 milliseconds.";
}, 1000);
}
function callback() {
output.innerHTML += "This function executed after some delay.";
}
</script>
</body>
</html>
Output
Following is the output of the above code −
The callTimer function executed Timer killed after 1000 milliseconds.
In the above output, users can observe that the callback function did not execute as we had killed the timer after 1000 milliseconds.