When to use setTimeout vs setInterval?
Tags: javascript, webdev, codenewbie, settimeout
Published: 2020-06-17 20:26:28

# Introduction

In this article, we will look at two popular time-based functions setTimeOut and setInterval in JavaScript.

# Scheduling

Any activity that is planned at a future time interval is generally referred to as scheduling. Both the functions allow you to execute a piece of JavaScript code/function at a certain point in the future.

# setTimeout()

The `setTimeout()` function is used when you wish to run your JavaScript function after a specified number of milliseconds from when the `setTimeout()` method was called. 

The general syntax of the method is:

```
window.setTimeout ( expression, timeout, param1, param2, ... );

//OR

setTimeout(expression, timeout, param1, param2, ...);

//NOTE: the params are optional
```

where `expression` is the JavaScript code to run after the `timeout` milliseconds have elapsed. The params are optional.

## setTimeOut() - Simple Expression

Let us look a simple example:

```jsx
setTimeout("console.log('\Hello World!')", 2000);
```

Things to note:

- Hello World will be displayed on the console after 2 seconds.
- The console.log statement is the expression.
- The timeout value is specified in milliseconds. Hence 2000 ms means 2s.
- The parameters are optional and are skipped in the example.

## setTimeOut() - Function

```jsx
setTimeout(function() {
   console.log('The mind is everything. What we think, we become!');
 }, 4000);
```

Things to note:

- "The mind is everything. What we think, we become!" will be displayed on the console after 4 seconds.
- The first parameter passed to the setTimeOut is an anonymous function.
- The second parameter is the timeout value specified in milliseconds.

There's another variation of the above code for improved code readability.

```jsx
function showMotivation() {
    console.log('The mind is everything. What we think, we become!');
}

setTimeout(showMotivation, 4000);
```

NOTE: The function name 'showMotivation' does not have a brackets when passed in as a parameter to the setTimeout function.

## setTimeout() with clearTimeout() & parameter

setTimeout() returns a numeric Id, that is used for tracking purposes. If there's any need to clear the timeout, then the numeric Id should be passed to the clearTimeout() function. Let us see the below example to understand this better.

```jsx
//Fruit Arrays  1 & 2 declaration & assignment
const fruitArr1 = ['apple', 'mango'];
const fruitArr2 = ['banana', 'papaya'];

//Function to display the selected fruit name
function displayFruit(fruit) {
    console.log(`The fruit selected is ${fruit}`);
}

//Function that'll call the 'displayFruit' method after setTimeout function is invoked
//If the fruit name is mango, the clearTimeout method will clear the timeout value and mango fruit will not be displayed
function checkFruit(fruitArr) {
    fruitArr.forEach(function(fruit) {
        const timeout = setTimeout(displayFruit, 2000, fruit);
        if (fruit === 'mango') {
            clearTimeout(timeout);
        }
    })
}

//Invoke checkFruit method
checkFruit(fruitArr1);
checkFruit(fruitArr2);
```

Things to note:

- The checkFruit method is invoked with fruitArr1 that contains apple &mango.
- Inside the checkFruit method, there's for loop initiated for each fruit.
- In the first iteration, the fruit name is 'apple' and the setTimeout function calls the displayFruit function and sets the timeout value to 2000 milliseconds and passes the fruit value as a parameter.
- A numeric value is assigned to the setTimeout function, but nothing happens in the clearTimeout function since the fruit name is 'apple'.
- In the second iteration, when the fruit name is mango, the "if fruit === 'mango'" check becomes true and the clearTimeout is invoked with the timeout value. Hence, the displayFruit function will not be invoked.

An additional point to note here is that `setTimeout()` doesn't stop the execution of the further script during the timeout period. It merely schedules the specified javascript code to be run at the specified time. After calling the `setTimeout()` function, the script continues normally, with the timer running in the background.

# setInterval()

The `setInterval()` function, as the name suggests is commonly used to set a delay for functions that are executed repeatedly. The `setInterval()` function is very closely related to `setTimeout()` and they even have same syntax:

```
setInterval ( expression, interval, param1, param2, ... );
```

The difference between setTimeout() and setInterval() is that setTimeout() triggers the function call once. While, the setInterval() triggers the function repeatedly after the specified interval of time.  

Let us look at a small example to understand the setInterval function.

```jsx
//Will output the text => The car is Tesla on the console
function displayCar() {
    console.log('The car is Tesla');
}

//The function 'displayCar' will be invoked repeatedly at a interval of 2 seconds
setInterval(displayCar, 2000);
```

The displayCar function wil be called repeatedly at the specified time interval of 2000 milliseconds or 2 seconds.

## setInterval with clearInterval() & parameter

Just like the method clearTimeout(), the clearInterval() is used to stop the function call happening repeatedly due to setTimeInterval. Let us look at the below code to understand better.

```jsx
//Declare a car array
const carArr = ['Tesla', 'Ford']

//Display the output -> The car is 'name of car' on console
function displayCar(car) {
    console.log(`The car is ${car}`);
}

//Check the car and display the name of car only if the car is Tesla
function checkCar(carArr) {
    carArr.forEach(function(car) {
        const interval = setInterval(displayCar, 2000, car);
        if (car !== 'Tesla') {
            clearInterval(interval);
        }
    })
}

//Invoke the checkCar function
checkCar(carArr);
```

Things to note:

- The example is very similar to the above fruits example, the only difference is that the setInterval(displaycar, 2000, car) method will be invoked for 'Tesla'.
- This means that at an interval of every 2 seconds the displayCar(car) function will be invoked with the car name as Tesla.
- Note that this will continue to happen even after the forEach block finishes execution. The execution will happen even after the checkCar() function also terminates.
- When the car name is not Tesla, the clearInterval function will clear the interval and the displayCar function will not be set to be invoked at the specified time interval.

# Conclusion

When you need to invoke a function once after a specified duration use setTimeout() function. But, if you need to invoke a function repeatedly at a specified interval of time, then you should use setInterval() function.

That's all folks! I hope the article was useful. Do let me know your thoughts, comments, and don't forget to share it with your friends/network. 

You might also like:

- [JavaScript Objects]([https://dev.to/skaytech/javascript-objects-31lb](https://dev.to/skaytech/javascript-objects-31lb))
- [JavaScript Functions]([https://dev.to/skaytech/all-about-javascript-functions-1l5f](https://dev.to/skaytech/all-about-javascript-functions-1l5f))
- [Immediately Invoking Function Expression - IIFE]([https://dev.to/skaytech/iife-immediately-invoking-function-expressions-1164](https://dev.to/skaytech/iife-immediately-invoking-function-expressions-1164))
- [Module & Revealing Design Patterns]([https://dev.to/skaytech/js-design-patterns-module-revealing-module-pattern-30c6](https://dev.to/skaytech/js-design-patterns-module-revealing-module-pattern-30c6))
- [History of ECMA/ES6/ES2015]([https://dev.to/skaytech/history-of-ecma-es5-es6-beyond-lpe](https://dev.to/skaytech/history-of-ecma-es5-es6-beyond-lpe))
- [The WAR - var vs let vs const]([https://dev.to/skaytech/the-war-var-vs-let-const-2a7l](https://dev.to/skaytech/the-war-var-vs-let-const-2a7l))