In Javascript, timers are used to execute code at specific times or execute code repeatedly after a certain amount of time. JavaScript provides two main types of timers: setTimeout() and setInterval(). Both allow you to schedule code to run after a specific delay, but they behave differently.
1. setTimeout()
- setTimeout() allows you to run a function or a block of code after a specified delay, but it only executes the code once.
- How it works:- You tell JavaScript, "Wait for this amount of time, and then run this code."
Syntax
setTimeout(function, delay, ...args);
Example
function sayHello() {
console.log("Hello, world!");
}
// Call sayHello() after 3 seconds (3000 milliseconds)
setTimeout(sayHello, 3000);
In this example, the sayHello
function will run after 3 seconds. The setTimeout()
function takes two arguments:
- The function you want to run (
sayHello
). - The delay in milliseconds (3000 milliseconds = 3 seconds).
- ...args (optional): Additional arguments that will be passed to the function when it executes.
Important Points:
- Non-blocking: setTimeout() does not block the rest of the code from executing. JavaScript continues to execute other instructions while it waits for the timeout.
- Milliseconds: The delay is specified in milliseconds, and the minimum delay is 1 millisecond.
- Single Execution: After the specified time, the callback function is invoked only once.
2. setInterval()
- setInterval() repeatedly runs a piece of code or function at a specified interval (in milliseconds), until you tell it to stop.
- How it works:- You tell JavaScript, "Keep running this code every X amount of time."
Syntax
setInterval(function, interval, ...args);
Example
function sayHello() {
console.log("Hello again!");
}
// Call sayHello() every 2 seconds (2000 milliseconds)
setInterval(sayHello, 2000);
- Here, the code inside setInterval() will run every 2 seconds.
Important Points:
- Non-blocking: Similar to setTimeout(), setInterval() is non-blocking. The browser continues running other tasks while it waits for the next interval.
- Repeats: Unlike setTimeout(), which runs only once, setInterval() will keep executing the callback function at the specified interval.
- Continuing Until Stopped: The function will run continuously at the given interval until it is cleared manually.
Clearing Timers
Sometimes, you might want to stop a timer before it completes. You can do this with clearTimeout() and clearInterval().
Stopping the setTimeout() timer:
If you want to cancel the timeout before it executes, you can use clearTimeout():
function sayHello() {
console.log("Hello, world!");
}
const timeoutId = setTimeout(sayHello, 4000);
// Stop the timeout before it runs
clearTimeout(timeoutId);
Stopping the setInterval() timer:
const intervalId = setInterval(sayHello, 1000);
// Stop the interval after 5 seconds
setTimeout(() => {
clearInterval(intervalId);
console.log("Interval timer stopped");
}, 5000);
- Here, we first start an interval that runs every second. Then, after 5 seconds, we use setTimeout() to stop the interval using clearInterval(intervalId).
Summary of Key Concepts:
- setTimeout(): Executes a function once after a specified delay.
- setInterval(): Executes a function repeatedly at specified intervals.
- clearTimeout() / clearInterval(): Used to cancel timers.
- Asynchronous nature: Timers do not block the execution of other code; they are added to the event queue and executed once the call stack is empty.
- Accuracy: Timer accuracy is not guaranteed due to other factors like heavy computations or browser limitations.
Top comments (0)