Do you really know how setimeout and setinterval work?
Tags: javascript, beginners, webdev, programming
Published: 2023-04-14 09:00:00

Hey Dev 😀, have you come across the, `setTimeout` and `setInterval` methods in JavaScript but you do not really know how they really work and the use cases for each of them. Don’t worry, In this article, you are going to learn what `setTimeout` and `setInterval` is examples and use cases for each of them. Let’s dive right into the article 😉.

## What is **`setTimeout` ?**
`setTimeout` is a method in JavaScript used to execute a function or a code block after a specified delay, represented in milliseconds.

Let’s break it down further

Have you ever gone to a meeting where you have to wait because the panel did not start at the right time? Like, maybe you went to a meeting at a particular time and perhaps the person in charge said you should wait for another some minutes again because something came up?

`setTimeout` is kind of like that. It's a way to tell the computer to wait for a certain amount of time before doing something. For example, you can tell the computer to wait for 5 seconds before showing a message on the screen.

### **`syntax`**
The syntax for **`setTimeout()`** is as follows:

```
setTimeout(function, delay, arg1, arg2, ...)
```
Here is what each parameter does 👇🏽
- **`function`**: the function to be executed after the delay.
- **`delay`**: the time delay in milliseconds before executing the function.
- **`arg1`**, **`arg2`**, etc.: optional arguments that will be passed to the function when it is called.

Now that we know what the syntax is, let’s take an example for a better understanding.

```
console.log('Hey!');

setTimeout(function () {
  console.log('Dev!');
}, 2000); // wait for 2 seconds

console.log('Goodbye!');
```
From the example above, we're using **`setTimeout()`** to wait for 2 seconds (2000 milliseconds) before printing **`'Dev'`** to the console. So, the output of this code will be:

```
Hello!
Goodbye!
Dev!
```
The code can also be written like this if you are an es6 fan. lol 👇🏽

```
setTimeout(() => {
  console.log('Dev!');
}, 2000); // wait for 2 seconds

console.log('Goodbye!');
```
Much better now right ? 🙂

💡 **`setTimeout()`** only executes the function once. If you need to execute a function repeatedly, you should use **`setInterval()`**

## What is **`setInterval` ?**
**`setInterval`** is a method that allows you to execute a specific code or function repeatedly at a defined time interval. It's like setting a timer that triggers a particular action every time the timer runs out. it is a little bit different. It's like telling the computer to do something over and over again at a regular interval.

### **`syntax`**
The syntax for **`setTimeout()`** is as follows:

```
setInterval(function, timeInterval);
```
Here is what each parameter does 👇🏽
- **`function`**: specifies the code or function that you want to execute
- **`timeInterval`**: specifies the time interval at which you want the function to execute. The time interval is usually specified in milliseconds.

Let’s see an example of how it works 👇🏽

```
let count = 0;

setInterval(() => {
  count++;
  console.log('Count is now ' + count);
}, 1000); // repeat every 1 second
```
From the example above, we’re using **`setInterval()`** to increment the **`count`** variable and print its value to the console every second (1000 milliseconds).

Here is the output 👇🏽

```
Count is now 1
Count is now 2
Count is now 3
Count is now 4
Count is now 5
till infinity and beyond....
```
Just so you know, the `count` variable is going to increment after every second which automatically means there won’t be an end.

So for us to stop or clear the interval after a particular period, and for us to do that, we are going to use the **`setTimeout()`** method.

*I’m sure you are getting the gist of what is happening already. lol*

Let’s take another example using the combination of both worlds 👇🏽

```
console.log('Lets count to 5 together!');

let count = 0;

let intervalId = setInterval(() => {
  count++;
  console.log('Say ' + count);
}, 1000); // repeat every 1 second

setTimeout(() => {
  clearInterval(intervalId);
}, 5000); // stop after 5 seconds
```
From the example above, we created **`intervalId`** function and we’re using **`setInterval()`** to increment the **`count`** variable and print its value to the console every second (1000 milliseconds).

We're also using **`setTimeout()`** to stop the interval after 5 seconds (5000 milliseconds). So, the output of this code will be:

```
Count is now 1
Count is now 2
Count is now 3
Count is now 4
Count is now 5
```
Unlike the previous example, the interval will stop, because we used **`clearInterval()`** to stop it.

Hope you see how they work together.

## USE CASES OF BOTH OF THEM
Here are some common use cases for **`setTimeout`** and **`setInterval`:**

### **`setTimeout`**
- **`setTimeout`**  can be used in delaying the execution of a function until a certain amount of time has passed, such as showing a notification after a certain delay.
- Animating elements on a web page, such as fading in an image after a certain delay.
- Handling user input, such as waiting for the user to finish typing before executing a search function.

### **`setInterval`**
- Updating a clock or timer on a web page, such as displaying the time every second.
- Implementing animations, such as a loading spinner that rotates continuously.
- Checking for changes or updates in data, such as polling a server for new messages or notifications.

## Conclusion
Congrats Dev for reading through this article 🎉. I really hope you learned something from it. You can also push yourself by building mini-projects around some of the use cases we talked about.

Till next time. Have a great weekend 😀