Ever wished JavaScript could just chill for a second before executing code? Or maybe you want it to do something over and over like an annoying alarm clock? Meet setTimeout and setInterval, JavaScript’s built-in procrastinators and infinite loop enablers!
1. What is setTimeout?
setTimeout lets you delay execution of a function after a specified time (in milliseconds). It’s like telling JavaScript, “Hey, do this… but, like, later.”
Example:
setTimeout(() => {
console.log("This message is fashionably late!");
}, 3000); // Executes after 3 seconds
Analogy: Like telling a friend to remind you about something in 3 seconds, but they’ll probably forget unless you handle it right.
2. What is setInterval?
setInterval repeatedly executes a function at specified time intervals until you tell it to stop. Think of it as JavaScript’s way of setting a recurring alarm.
Example:
let counter = 1;
let intervalId = setInterval(() => {
console.log(`Ping! ${counter}`);
counter++;
}, 2000); // Runs every 2 seconds
Analogy: Like a gym trainer who keeps shouting "One more rep!" every two seconds until you collapse. 🏋️♂️
3. Stopping setTimeout and setInterval
Once setTimeout is scheduled, you can cancel it using clearTimeout(). Similarly, setInterval can be stopped using clearInterval().
Example:
let timeoutId = setTimeout(() => {
console.log("You won’t see this message!");
}, 5000);
clearTimeout(timeoutId); // Cancels the timeout before it executes
clearInterval(intervalId); // Stops the recurring madness
Analogy: Like deciding not to go to the gym after setting multiple alarms.
4. Practical Use Cases
- Delaying Execution: Loading spinners, animations, lazy-loading content.
- Repeating Tasks: Auto-refresh, countdown timers, periodic API calls.
- Creating Chaos: Annoying pop-ups, endless alerts (please don’t).
Conclusion
setTimeout and setInterval are your go-to tools for controlling time in JavaScript. Use them wisely, or risk creating an infinite loop of doom!
0 Comments:
Posting Komentar