Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
communitycreator

How to use setTimeout in JavaScript

Programming Bytes

setTimeout allows us to schedule a function to be executed after a specific amount of time.

Syntax

setTimeout(function|code, [delay_time], [arg1], [arg2], ...);

The parameters of setTimeout function are:

  • function | code — the function or string value to be executed after the delay time expires.
  • delay_time — the time in milliseconds (1000 milli_seconds = 1 second), after which the function will be executed. The value is 0 by default.
  • arg1, arg2, ... — extra arguments passed to the function.

Schedule a function

Let’s say we need to print a message after one second.

Console

The above code will print “Hi Customer” after one second.

If we pass a string as the first argument, then JavaScript will execute the String using eval.

Console

It is not recommended to pass.

Cancel the scheduled function’s execution

When we call setTimeout, it will return a unique numeric id. We can then pass this id to the clearTimeout function to cancel the execution of the scheduled function.

Console

When we execute the above code, the message will not be printed because we’ve cleared the scheduled function.

Zero delay setTimeOut

When we don’t send the delayTime, then the delayTime is set to zero, meaning that the timeout function will execute immediately in the next event cycle.

Console

When JavaScript executes the test function:

  • it detects setTimeout and pushes the printMsg function to the event loopan area to store functions to be executed next. The function that is inserted first in the event loop will be executed first.

  • after completion of the test function, JavaScript will check if there is any function available in the event loop. JavaScript finds printMsg function is waiting for its execution, so JavaScript will execute the printMsg function.

try…catch in setTimeout

In setTimeout, the exception on the callback function will not be caught if we surround the setTimeout with try..catch.

function test(){
  const a = 7;
  a = 10;
}

try{
  setTimeout(test, 100);
} catch(e) {
  console.log(e);
}

The code above will throw an error because the test function will be executed after 100 milliseconds. Before executing the test function, the JavaScript engine has already left the try...catch area.

To handle this, we need to catch the exception inside the callback function.

Console

this in setTimeout

When you pass a method reference to setTimeout, the window inside the callback function is this.

let user = {
  detail : { age: 20},
  printAge() {
    console.log(this);
    console.log(this.detail.age);
  }
}
user.printAge(); // print user object and 20 
setTimeout(user.printAge, 1000); // print window and throws an error

To solve this, use an arrow function as a callback function.

Console

Practical example

Debounce

Based on an event we can register an operation to be executed after some delay. If the same event occurs again, then the old registered operation is deleted and a new operation is registered. Debounce groups multiple events into a single event.

Consider an input box. Once the user types something in the input, we need to update the content based on the input value. We can use debounce here because we don’t need to fetch data for each letter typed by the user; instead, we wait for some milliseconds and then send a request.

Type something in the text box below to see the code in action:

Console

The fetchData method will be executed 300 milliseconds after the user stopped typing.

RELATED TAGS

javascript
communitycreator
RELATED COURSES

View all Courses

Keep Exploring