setTimeout() in JavaScript

setTimeout() in JavaScript

In JavaScript, sometimes we need to run a block of code after waiting for some time. For this, you can use the JavaScript setTimeout() function. By using this method, you can delay the execution of the code by a set number of milliseconds.

In this blog, we will discuss how the JavaScript setTimeout() function works, and how to use it, and we will see some examples to understand it better.

Table of Contents:

What is the setTimeout() function in JavaScript?

The setTimeout() function in JavaScript is used to add delay in the execution of the code. It will run the code after waiting for a certain amount of time. This delay is counted in milliseconds (1 second = 1000 milliseconds). You can use this function in many cases like creating timed effects, waiting before running a code, or delaying an action.

Why is setTimeout() function useful?

  • Delaying execution: You can schedule a task to wait for some time before running.
  • Creating animations or timed events: You can use it to control the timing of animation or to add delay between events.

Syntax:

setTimeout(function, delay);

Parameters:

  1. Function: This is the block of code you want to execute after the delay. It can be an anonymous function, a named function, or a callback function.
  2. Delay: This is the waiting time to execute the code. It is in milliseconds and 1000 milliseconds is equal to 1 second. For example, if you want to set the delay for 2 seconds, use 2000.

Return Value:

The setTimeout() function returns a special timer ID which is a positive number. This number will help you identify the timer that was created. You can use this timer ID with the clearTimeout() function to cancel the timer before it runs.

Let’s see an example of the setTimeout() function.

Example: In this example, we will print a message after a delay of 2 seconds.

setTimeout(function() {
  console.log("Hey, this is Intellipaat!");
}, 2000);

Output:

How does the JavaScript setTimeout() function work?

To understand the working of the JavaScript setTimeout() function, we need to learn about 2 things:

1. Event Loop

JavaScript runs the code one step at a time. So to do multiple tasks, it uses the event loop. Let’s see what it does:

  • Call stack: JavaScript uses this to run functions. It runs one function at a time.
  • Callback queue: When you use the setTimeout() function, it adds the code to this queue after the delay time.
  • Event loop: The event loop checks the call stack. When there is no code running, it takes a task from the callback queue and adds it to the call stack to execute.

So when you use the setTimeout() function, JavaScript doesn’t run the code immediately. It waits for the delay time and then adds the code to the queue to execute it later.

2. Timing Behavior and Precision

The setTimeout() function looks very straightforward but there are some things you should know about:

  • Delay isn’t always exact: If you set a delay of 3 seconds, it does not guarantee execution exactly after 3 seconds It also depends on what else is going on in the code.
    For example, if there are other tasks that are currently running then it will wait for them to finish first.
  • Minimum delay: The minimum delay in the setTimeout() function is 4 milliseconds but it takes longer than that because of how JavaScript handles things.

Example: In this example, we will print a message with a delay of 3 seconds.

console.log("Start");
setTimeout(function() {
  console.log("This runs after 3 seconds");
}, 3000);
console.log("End");

Output:

Explanation:

  • “Start” will be printed first.
  • setTimeout() will wait for 3 seconds and will not run until the current code finishes.
  • “End” will be printed immediately after setTimeout().
  • And at last, after 3 seconds, the message “This runs after 3 seconds” will be displayed.

Example Usage of setTimeout()

Here, we will see some other example usage of the JavaScript setTimeout() function:

Example 1: Delaying Code Execution

You can use the JavaScript setTimeout() function to delay the execution of the code which is very useful in your web page like creating an animation or showing a notification.

console.log("Hello");
setTimeout(function() {
  console.log("This is Intellipaat!");
}, 3000);
console.log("Goodbye");

Output:

Example 2: Using setTimeout() in Loops

You can also use the JavaScript setTimeout() function inside loops to delay the multiple tasks. However, using it in loops can work differently because of how JavaScript handles asynchronous code.

for (let i = 1; i <= 5; i++) {
  setTimeout(function() {
    console.log("Message number " + i);
  }, i * 1000);
}

Output:

Here,

  • The loop will run 5 times but because of setTimeout(), each message will get delayed by 1, 2, 3, 4, and 5 seconds respectively.

Example 3: Add Time in a String Instead of Milliseconds

In JavaScript, to use time as a string with the setTimeout() function, first, you need to convert the string into milliseconds and then pass it to the setTimeout() function. Let’s see how you can do this:

function customDelayToMilliseconds(delay) {
  if (delay.includes('s')) {
    return parseInt(delay, 10) * 1000;
  }
  return parseInt(delay);
}

let delay = "3s";
let delayInMilliseconds = customDelayToMilliseconds(delay);
setTimeout(function() {
  console.log("Hi, this is Intellipaat");
}, delayInMilliseconds);

Output:

Here:

  • The function customDelayToMilliseconds(delay) converts the string “3s” to 3000 milliseconds. (3s = 3*1000 = 3000 milliseconds)
  • The setTimeout() function will use this value to wait for the 3000 milliseconds and then run the callback function to print the message.

Clearing setTimeout() with clearTimeout()

In JavaScript, you can easily clear a timeout you have set with the setTimeout() function before it runs. You can do it by using the clearTimeout() function. It is used when you don’t need that timeout action after some specified time.

Syntax:

clearTimeout(timeoutID);
  • timeoutID is the ID that is returned by the setTimeout() function when you create the timeout. You can use this ID to refer to the timeout you want to cancel.

Example: Let’s see an example of how setTimeout() and clearTimeout() function work together.

let timeoutID = setTimeout(function() {
  console.log("This will never run.");
}, 5000);
clearTimeout(timeoutID);
console.log("Timeout cleared, so the message will not appear.");

Output:

Here,

  • The above part of the code should have run after 5 seconds but since we cleared it with the clearTimeout() function, it didn’t happen.

Passing Arguments to setTimeout()

In JavaScript, you can pass the arguments to the function you want to run inside setTimeout() in two ways. By using the anonymous function and by using the bind() method.

1. Using an Anonymous Function

You can pass the arguments by defining an anonymous function inside the setTimeout() function.

Example:

function greet(name) {
  console.log("Hi, " + name + "!");
}
setTimeout(function() {
  greet("Intellipaat");
}, 2000);

Output:

2. Using bind() Method

You can also pass arguments using the bind() method to the function when it is called by setTimeout().

Example:

function greet(name) {
  console.log("Hi, " + name + "!");
}
setTimeout(greet.bind(null, "Intellipaat"), 2000);

Output:

Handling Multiple Timers

In JavaScript, when you need to run multiple tasks with delay, you can use the setTimeout() function to manage them in many different ways. Let’s see how you can handle multiple timers, stack them, and control them when each function runs.

1. Stacking Timeouts

You can create multiple setTimeout() to run multiple tasks one after another. Each task will run after a delay and they will be executed in order.

Example:

setTimeout(function() {
  console.log("First task after 1 second.");
}, 1000);
setTimeout(function() {
  console.log("Second task after 2 seconds.");
}, 2000);
setTimeout(function() {
  console.log("Third task after 3 seconds.");
}, 3000);

Output:

2. Managing Delayed Functions

Sometimes you want to repeat a task after some delay until a condition is met. You can use setTimeout() to call a function multiple times.

Example:

let counter = 0;
function repeatTask() {
  counter++;
  console.log("Task done, counter is", counter);
  if (counter < 5) {
    setTimeout(repeatTask, 1000);
  }
}
setTimeout(repeatTask, 1000);

Output:

3. Clearing and Controlling Multiple Timeouts

You can also clear a timeout if you don’t need it anymore. You can do this by saving the timeout ID and using clearTimeout().

Example:

let timeout1 = setTimeout(function() {
  console.log("It will run after 3 seconds.");
}, 3000);

let timeout2 = setTimeout(function() {
  console.log("It will run after 5 seconds.");
}, 5000);
clearTimeout(timeout1);
console.log("Timeout 1 has been cleared.");

Output:

Problem with ‘this’ in JavaScript setTimeout() 

When you are using setTimeout(), the ‘this’ keyword can change its meaning and it does not refer to the object you want it to. It is because setTimeout() runs in its own function and it does not automatically keep the same ‘this’ as the outer object.

Example:

const person = {
  name: "Intellipaat",
  greet: function() {
    console.log("Before setTimeout: " + this.name);
    setTimeout(function() {
      console.log("Inside setTimeout: " + this.name);
    }, 2000);
  }
};
person.greet();

Output:

Explanation:

  • Before setTimeout(): this.name works and prints “Intellipaat” because ‘this’ refers to the person object.
  • Inside setTimeout(): this.name doesn’t work. It prints undefined or refers to the global object because ‘this’ inside setTimeout() doesn’t refer to the person object anymore. 

Solution 1: Using Arrow Function

An arrow function does not have its own ‘this’. It inherits ‘this’ from the context where the arrow function was created.

Example:

const person = {
  name: "Intellipaat",
  greet: function() {
    console.log("Before setTimeout: " + this.name);
    setTimeout(() => {
      console.log("Inside setTimeout (arrow function): " + this.name);
    }, 2000);
  }
};
person.greet();

Output:

Solution 2: Using bind()

You can also use bind() method to correct the context of ‘this’. This will allow you to bind ‘this’ to the given object.

Example:

const person = {
  name: "Intellipaat",
  greet: function() {
    console.log("Before setTimeout: " + this.name);
    setTimeout(function() {
      console.log("Inside setTimeout (using bind): " + this.name);
    }.bind(this), 1000);
  }
};
person.greet();

Output:

Alternatives to setTimeout()

In JavaScript, there are more ways to handle delays and repeated tasks. The two common alternatives are setInterval() and using Promises with setTimeout().

1. Using setInterval()

The setTimeout() runs one function at a time after a delay but setInterval() repeatedly runs a function with regular intervals.

Example:

let count = 0;
let intervalID = setInterval(function() {
  count++;
  console.log("Task done, count:", count);
  if (count === 5) {
    clearInterval(intervalID);
    console.log("Interval stopped.");
  }
}, 1000);

Output:

When to use:

  • It is used when you want to run a task multiple times at a regular time like you want to check something every few seconds.

2. Using Promises with setTimeout()

Another way to handle delays is by using promises with setTimeout(). It allows you to use async/await to write more clear and understandable code. You can use it when you have multiple tasks that depend on each other.

Example:

function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}
async function runTasks() {
  console.log("Task 1 starts");
  await delay(2000);
  console.log("Task 1 ends after 2 seconds");
  console.log("Task 2 starts");
  await delay(1000);
  console.log("Task 2 ends after 1 second");
}
runTasks();

Output:

When to use:

  • It is used when you have multiple tasks to perform with delays and you want to avoid complicated nested callbacks.

Advanced Usage of setTimeout()

Let’s see some advanced use cases where the setTimeout() function can be very useful:

1. Chaining setTimeout() Calls

You can call setTimeout() multiple times instead of using setInterval(). This will allow you to control the time between each call and change it if needed.

Example:

function repeatTask() {
  console.log("Hi, Intellipaat!");
  setTimeout(repeatTask, 2000);
}
repeatTask();

Output:

2. Using setTimeout() to Simulate API Delays

You can use setTimeout() to make believe there’s a delay when you’re testing something like an API response. It mimics slow network responses.

Example:

console.log("Request sent...");
setTimeout(function() {
  console.log("Response received after 3 seconds");
}, 3000);

Output:

3. Using setTimeout() for Debouncing

Debouncing helps you avoid calling a function multiple times in a short period. For example, it will wait for you to stop typing before running a search function.

Example:

let timeout;
function search(query) {
  clearTimeout(timeout);
  timeout = setTimeout(() => {
    console.log("Searching for:", query);
  }, 1000);
}
search("Intellipaat");

Output:

4. Prioritizing Tasks Using setTimeout()

You can also use setTimeout() to run less important tasks later. This helps you to run more important tasks first.

Example:

console.log("Important task starting...");
setTimeout(function() {
  console.log("Less important task, delayed");
}, 2000);
console.log("Important task completed!");

Output:

Conclusion

So far in this blog, we have learned what is JavaScript setTimeout() function, how it works, how to use it, how to clear it and what are its alternatives. We also saw some examples of using the setTimeout() function. The setTimeout() function in JavaScript is used to add delay in the execution of the code and this delay is counted in milliseconds (1 second = 1000 milliseconds). You can also clear this timeout by using clearTimeout() function.

FAQs – JavaScript setTimeout()

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner