Do you really know how setimeout and setinterval work?
?? Hey Devs! Are you familiar with setTimeout and setInterval methods in JavaScript, but unsure about their inner workings and real-world applications? ?? No worries! This article is your guide to understanding these functions and their use cases. Let's dive in! ??
What is setTimeout? ??
Have you ever been stuck waiting for a meeting to start, only for it to be delayed? Just like that, setTimeout lets your code wait before executing. It's like telling your computer to chill for a bit before proceeding. For instance, waiting 5 seconds before displaying a message. Check out the syntax ??
setTimeout(function, delay, arg1, arg2, ...);
Let's take a quick example
console.log('Hey!')
setTimeout(function () {
? console.log('Dev!');
}, 2000); // wait for 2 seconds
console.log('Goodbye!');
In essence, it creates a brief pause, then prints 'Hey!', waits for 2 seconds, prints 'Dev!', and lastly logs 'Goodbye!'. This demonstrates how setTimeout lets you control the timing of actions in your code. ????
One thing to note is that setTimeout only fires once. Need repetition? Enter setInterval.
What is setInterval? ??
setInterval is like a metronome. It triggers your code repeatedly at set intervals. It's like instructing your computer to do something over and over on a timer. Let's break it down ??
setInterval(function, timeInterval);
Let's also see an example
let count = 0
setInterval(() => {
? count++;
? console.log('Count is now ' + count);
}, 1000); // repeat every 1 second
Here is the output
Count is now 1
Count is now 2
Count is now 3
Count is now 4
Count is now 5
...and on it goes!
Use Cases! ??
When should you use these functions?
setTimeout can be your go-to for:
setInterval shines when:
?? To wrap it up, Devs, setTimeout, and setInterval are like your time-management allies in JavaScript. With setTimeout, you can make your code pause and then perform an action after a set delay. Meanwhile, setInterval lets you orchestrate repetitive actions at fixed intervals.
Remember:
If you want to learn more about these powerful functions, here is a link to a well-detailed article I wrote on it