Use setTimeout
and setInterval
for timing operations and animations.
setTimeout()
, which runs code once after a delay, and setInterval()
, which runs code repeatedly at specified intervals. These functions are essential for animations, polling data, or scheduling tasks in web applications.
Examples of using setTimeout
and setInterval
:
// setTimeout - runs once after 2 seconds
setTimeout(() => {
console.log("Executed after 2 seconds");
}, 2000);
// setInterval - runs every 1 second
const intervalId = setInterval(() => {
console.log("Runs every second");
}, 1000);
// Clear the interval after 5 seconds
setTimeout(() => {
clearInterval(intervalId);
console.log("Interval cleared");
}, 5000);
This code demonstrates:
setTimeout
to delay code execution.setInterval
for repeated execution.clearInterval
to stop repeated execution.setTimeout()
and setInterval()
are asynchronous functions that control timing in JavaScript.
callback
function once after delay
milliseconds.callback
every delay
milliseconds.setTimeout
.setInterval
.These timing methods are commonly used in creating animations, scheduling API requests, or deferring execution of heavy computations.
Q1: Which function is used to execute a task after a delay?
Answer: D. setTimeout
Q2: What does clearInterval
do?
Answer: C. Stops a repeating interval
Q3: What is returned by setTimeout
and setInterval
?
Answer: D. A unique ID
Q4: How can you stop a setTimeout
before it runs?
Answer: A. clearTimeout(id)