settimeout js callback

How to Pass Parameter to SetTimeout Callback

SetTimeout function allows you to set timeout in JavaScript, that is, execute a function or piece of JS code after a given time interval. Generally, we just call a function within SetTimeout(). Sometimes you may need to pass parameter to SetTimeout callback section. In this article, we will learn how to do this.


How to Pass Parameter to SetTimeout Callback

Here is the syntax of SetTimeout function.

setTimeout(function,milliseconds);

Sometimes you may want to pass parameter to callback function of setTimeout. Let us say you have the following function.

function hello(day){
  alert('today is '+day);
}

Let us say you want to pass the day input argument of above hello() function from within setTimeout().

Here is how you can do it. You need to create an anonymous function as the callback and pass the parameter. Here is an example for it.

function hi(day)
{
  if (day=='Sunday')
  {

    setTimeout(function(){hello(day)},4000);
  }
}

function hello(day)
{
  alert('today is '+day);
}

Please note the following line in above code. We accept the input parameter day from function, and then pass it to hello() function, called within an anonymous function defined as callback for SetTimeout().

    setTimeout(function(){hello(day)},4000);

Alternatively, you can also call it as. In this case we use bind() function as our callback function call.

setTimeout(hello.bind(null, day), 4000);

Please note, the following syntax WILL NOT WORK although it seems to be intuitive.

setTimeout("hello(day)",4000);

In this article, we will learn how to pass parameter to setTimeout.

Also read:

How to Generate Random String from JavaScript
How to Fix PostgreSQL Error: Fatal Role Does Not Exist
How to Install Python Package Using Script
How to Iterate Over Python List in Chunks
How to Create Python Dictionary from String

Leave a Reply

Your email address will not be published.