Using setTimeout and setInterval in JavaScript
In JavaScript, setTimeout() andsetInterval() are two very useful functions for working with timers. They allow you to execute code after a delay or repeatedly at set intervals.
Syntax:
The basic syntax for these functions is:
- setTimeout: setTimeout(func, delay), where funcis the function to execute and delay is the time in milliseconds before executing it.
- setInterval: setInterval(func, interval), wherefunc is the function to execute and interval is the time in milliseconds between executions.
- clearTimeout: Stops the execution of a function scheduled with setTimeout.
- clearInterval: Stops the repeated execution of a function scheduled with setInterval.
Examples:
`setTimeout`
setTimeout(() => { console.log("Hello after 2 seconds"); }, 2000);
Explanation:
In this example, the function will execute after a delay of 2000 milliseconds (2 seconds). It's useful for performing tasks with a specific delay.
`setInterval`
const id = setInterval(() => { console.log("This repeats every second"); }, 1000);
Explanation:
This code uses setInterval to execute the function every 1000 milliseconds (1 second). It's useful for repetitive tasks, such as updating a timer or performing periodic queries.
`clearTimeout`
const timeoutId = setTimeout(() => { console.log("This will not execute"); }, 5000); clearTimeout(timeoutId);
Explanation:
This example shows how to cancel a setTimeout before it executes. The function scheduled for 5 seconds will never run because we use clearTimeout with the timeout identifier.
clearInterval
const intervalId = setInterval(() => { console.log("This will repeat every second"); }, 1000); setTimeout(() => { clearInterval(intervalId); console.log("Interval stopped"); }, 5000);
Explanation:
In this example, setInterval executes a function every second, but it stops after 5 seconds thanks toclearInterval. This is a common pattern for stopping repetitive tasks when they are no longer needed.
Purpose:
These functions are highly useful for creating animations, making periodic requests, or executing tasks after a delay.
Exercises
The rest of the content is available only for registered and premium users!
JavaScript Concepts and Reference
Functions
Objects in JavaScript
Arrays
DOM (Document Object Model)
Error Handling
Promises and Asynchronicity
Modules in JavaScript
ES6 and Advanced Features
What does the setTimeout function do in JavaScript? What are setTimeout and setInterval in JavaScript? What is the difference between Settimeout and Setinterval in LWC? What is the difference between nested Settimeout and Setinterval? setInterval JavaScript setTimeout JavaScript clearInterval javascript setTimeout JavaScript example setInterval vs setTimeout setInterval React setTimeout jQuery Setinterval javascript function