Javascript settimeout method

Learn how to use settimeout method in javascript.

There may come scenario when you want to delay execution of code or trigger something after a particular time. In this situations you can use setTimeout method.

Example

setTimeout(function(){
  console.log('I will be visible after 1 sec delay');
}, 1000);

//"I will be visible after 1 sec delay"

setTimeout method calls a function or executes a statement after a delay of specified number of milliseconds.


Syntax

setTimeout(function, milliseconds, param1, param2, ...);

function: Required

The function that needs to be executed.

milliseconds: Optional

Time in milliseconds to wait before executing the function. Default is 0.

params: Optional

Extra parameters that needs to be passed to the function which will be executed (Works after IE9).

Return value

Each setTimeout method returns a numeric ID that is assigned to it. It can be used to clear the timer.

setTimeout(function() {
  console.log('I will work after 2 seconds');
}, 2000);

//"I will work after 2 seconds"

setTimeout function is executed only once. If you want to call something repeatedly then use setInterval.


Calling predefined function

let greet = (param1, param2) => {
  console.log(`${param1} is ${param2}`)
}

setTimeout(function(){ greet('Prashant', 'Happy') }, 2000);

//"Prashant is Happy"

Passing params separately

let greet = (param1, param2) => {
  console.log(`${param1} is ${param2}`)
}

setTimeout(greet, 2000, 'Prashant', 'Happy');

//"Prashant is Happy"

It will not work in IE9 and less. Use the above method if you want.


Handling this

Handling this with setTimeout was not so easy before, We had to use a workaround for that.

let increment = {
  count: 1,
  start: function(){
    setTimeout(function(){
      console.log(++that.count);
    }, 1000)
  }
}

increment.start();
//NaN

Now this inside the setTimeout is referring to its context but we want to access the parent’s this. Incrementing the undefined value is resulting in NaN.

So we assign the parent’s this to another variable and use it.

let increment = {
  count: 1,
  start: function(){
    //Assign this to variable that
    var that = this;
    setTimeout(function(){
      console.log(++that.count);
    }, 1000)
  }
}

increment.start();
//2

But with introduction of => function in ES6 we can handle this easily.

let increment = {
  count: 1,
  start: function(){
    setTimeout(() => {
      console.log(++this.count);
    }, 1000)
  }
}

increment.start();
//2

Clearing setTimeout

let start = setTimeout(() => {
   console.log('I just started');
   clearMe();
}, 2000);

let clearMe = () => {
   clearTimeout(start);
}

//"I just started"

clearTimeout method clears the timer set by the setTimeout. It takes setTimeout ID as input which is required.


Using setTimeout to create setInterval

We can recursively call the function to mimic the setInterval.

let increment = (num) => {
  setTimeout(() => {
     //print the num
     console.log(num);

     //increment the value
     num = num + 1;

     //recursively call the function
     increment(num);

  }, 1000);
}
 
increment(1);

//1
//2
//3
//4

How to use settimeout

There are many times where javascript settimeout method can be used.

Here is the one situation like this. Suppose user saves some data and a popup or message is shown to notify that your data is saved successfully.

Now after few second if you want to automatically hide this message then you can use setTimeout for this.

//To show the message
let showMessage = () => {
   $('.show-message').text('You have saved the data successfully');
   hideMessage();
}

//To hide the message
let hideMessage = () => {
   setTimeout(() => {
     $('.show-message').hide();
   }, 5000);
} 

showMessage();

Leave a Reply

Your email address will not be published. Required fields are marked *