javascript angular - How can I pass a parameter to a setTimeout()callback?

variable undefined (17)

After doing some research and testing, the only correct implementation is:

setTimeout(yourFunctionReference, 4000, param1, param2, paramN);

setTimeout will pass all extra parameters to your function so they can be processed there.

The anonymous function can work for very basic stuff, but within instance of a object where you have to use "this", there is no way to make it work. Any anonymous function will change "this" to point to window, so you will lose your object reference.

I have some JavaScript code that looks like:

function statechangedPostQuestion()
  if (xmlhttp.readyState==4)
    var topicId = xmlhttp.responseText;

function postinsql(topicId)

I get a error that topicId is not defined Everything was working before i used the setTimeout() function.

I want my postinsql(topicId) function to be called after some time. What should i do?

@Jiri Vetyska thanks for the post, but there is something wrong in your example. I needed to pass the target which is hovered out (this) to a timed out function and I tried your approach. Tested in IE9 - does not work. I also made some research and it appears that as pointed here the third parameter is the script language being used. No mention about additional parameters.

So, I followed @meder's answer and solved my issue with this code:

$('.targetItemClass').hover(ItemHoverIn, ItemHoverOut);

function ItemHoverIn() {
 //some code here

function ItemHoverOut() {
    var THIS = this;
        function () { ItemHoverOut_timeout(THIS); },
function ItemHoverOut_timeout(target) {
    //do something with target which is hovered out

Hope, this is usefull for someone else.

My answer:

setTimeout((function(topicId) {
  return function() {
})(topicId), 4000);


The anonymous function created returns another anonymous function. This function has access to the originally passed topicId, so it will not make an error. The first anonymous function is immediately called, passing in topicId, so the registered function with a delay has access to topicId at the time of calling, through closures.


This basically converts to:

setTimeout(function() {
  postinsql(topicId); // topicId inside higher scope (passed to returning function)
}, 4000);

EDIT: I saw the same answer, so look at his. But I didn't steal his answer! I just forgot to look. Read the explanation and see if it helps to understand the code.

You can try default functionality of 'apply()' something like this, you can pass more number of arguments as your requirement in the array

function postinsql(topicId)

In general, if you need to pass a function as a callback with specific parameters, you can use higher order functions. This is pretty elegant with ES6:

const someFunction = (params) => () => {
  //do whatever

setTimeout(someFunction(params), 1000);

Or if someFunction is first order:

setTimeout(() => someFunction(params), 1000); 


 setTimeout("postinsql(topicId)", 4000);


 setTimeout("postinsql(" + topicId + ")", 4000);

or better still, replace the string expression with an anonymous function

 setTimeout(function () { postinsql(topicId); }, 4000);


Brownstone's comment is incorrect, this will work as intended, as demonstrated by running this in the Firebug console

(function() {
  function postinsql(id) {
  var topicId = 3
  window.setTimeout("postinsql(" + topicId + ")",4000); // outputs 3 after 4 seconds

Note that I'm in agreeance with others that you should avoid passing a string to setTimeout as this will call eval() on the string and instead pass a function.

I recently came across the unique situation of needing to use a setTimeout in a loop. Understanding this can help you understand how to pass parameters to setTimeout.

Method 1

Use forEach and Object.keys, as per Sukima's suggestion:

var testObject = {
    prop1: 'test1',
    prop2: 'test2',
    prop3: 'test3'

Object.keys(testObject).forEach(function(propertyName, i) {
    setTimeout(function() {
    }, i * 1000);

I recommend this method.

Method 2

Use bind:

var i = 0;
for (var propertyName in testObject) {
    setTimeout(function(propertyName) {
    }.bind(this, propertyName), i++ * 1000);


Method 3

Or if you can't use forEach or bind, use an IIFE:

var i = 0;
for (var propertyName in testObject) {
    setTimeout((function(propertyName) {
        return function() {
    })(propertyName), i++ * 1000);

Method 4

But if you don't care about IE < 10, then you could use Fabio's suggestion:

var i = 0;
for (var propertyName in testObject) {
    setTimeout(function(propertyName) {
    }, i++ * 1000, propertyName);

Method 5 (ES6)

Use a block scoped variable:

let i = 0;
for (let propertyName in testObject) {
    setTimeout(() => console.log(testObject[propertyName]), i++ * 1000);

Though I would still recommend using Object.keys with forEach in ES6.

setTimeout(function() {
}, 4000)

You need to feed an anonymous function as a parameter instead of a string, the latter method shouldn't even work per the ECMAScript specification but browsers are just lenient. This is the proper solution, don't ever rely on passing a string as a 'function' when using setTimeout() or setInterval(), it's slower because it has to be evaluated and it just isn't right.


As Hobblin said in his comments to the question, now you can pass arguments to the function inside setTimeout using Function.prototype.bind()


setTimeout(postinsql.bind(null, topicId), 4000);

The answer by David Meister seems to take care of parameters that may change immediately after the call to setTimeout() but before the anonymous function is called. But it's too cumbersome and not very obvious. I discovered an elegant way of doing pretty much the same thing using IIFE (immediately inviked function expression).

In the example below, the currentList variable is passed to the IIFE, which saves it in its closure, until the delayed function is invoked. Even if the variable currentList changes immediately after the code shown, the setInterval() will do the right thing.

Without this IIFE technique, the setTimeout() function will definitely get called for each h2 element in the DOM, but all those calls will see only the text value of the last h2 element.

  // Wait for the document to load.
  $(document).ready(function() {
  $("h2").each(function (index) {

    currentList = $(this).text();

    (function (param1, param2) {
        setTimeout(function() {
            $("span").text(param1 + ' : ' + param2 );
        }, param1 * 1000);

    })(index, currentList);

Note that the reason topicId was "not defined" per the error message is that it existed as a local variable when the setTimeout was executed, but not when the delayed call to postinsql happened. Variable lifetime is especially important to pay attention to, especially when trying something like passing "this" as an object reference.

I heard that you can pass topicId as a third parameter to the setTimeout function. Not much detail is given but I got enough information to get it to work, and it's successful in Safari. I don't know what they mean about the "millisecond error" though. Check it out here:

Some answers are correct but convoluted.

I am answering this again, 4 years later, because I still run into overly complex code to solve exactly this question. There IS an elegant solution.

First of all, do not pass in a string as the first parameter when calling setTimeout because it effectively invokes a call to the slow "eval" function.

So how do we pass in a parameter to a timeout function? By using closure:

    //thanks to closure, topicid is visible here

if (xhr.readyState==4){

Some have suggested using anonymous function when calling the timeout function:

if (xhr.readyState==4){

The syntax works out. But by the time settopic is called, i.e. 4 seconds later, the XHR object may not be the same. Therefore it's important to pre-bind the variables.

I think you want:

setTimeout("postinsql(" + topicId + ")", 4000);

this works in all browsers (IE is an oddball)

setTimeout( (function(x) {
return function() {
})(topicId) , 4000);

How i resolved this stage ?

just like that :

setTimeout((function(_deepFunction ,_deepData){
    var _deepResultFunction = function _deepResultFunction(){
    return _deepResultFunction;
})(fromOuterFunction, fromOuterData ) , 1000  );

setTimeout wait a reference to a function, so i created it in a closure, which interprete my data and return a function with a good instance of my data !

Maybe you can improve this part :


// change to something like :
_deepFunction.apply(contextFromParams , args); 

I tested it on chrome, firefox and IE and it execute well, i don't know about performance but i needed it to be working.

a sample test :

myDelay_function = function(fn , params , ctxt , _time){
setTimeout((function(_deepFunction ,_deepData, _deepCtxt){
            var _deepResultFunction = function _deepResultFunction(){
        _deepCtxt , _deepData);
        return _deepResultFunction;
    })(fn , params , ctxt)
, _time) 

// the function to be used :
myFunc = function(param){ console.log(param + }
// note that we call

// a context object :
myObjet = {
    id : "myId" , 
    name : "myName"

// setting a parmeter
myParamter = "I am the outer parameter : ";

//and now let's make the call :
myDelay_function(myFunc , myParamter  , myObjet , 1000)

// this will produce this result on the console line :
// I am the outer parameter : myName

Maybe you can change the signature to make it more complient :

myNass_setTimeOut = function (fn , _time , params , ctxt ){
return setTimeout((function(_deepFunction ,_deepData, _deepCtxt){
            var _deepResultFunction = function _deepResultFunction(){
                _deepFunction.apply(  _deepCtxt , _deepData);
        return _deepResultFunction;
    })(fn , params , ctxt)
, _time) 

// and try again :
for(var i=0; i<10; i++){
   myNass_setTimeOut(console.log ,1000 , [i] , console)

And finaly to answer the original question :

 myNass_setTimeOut( postinsql, 4000, topicId );

Hope it can help !

ps : sorry but english it's not my mother tongue !

This is a very old question with an already "correct" answer but I thought I'd mention another approach that nobody has mentioned here. This is copied and pasted from the excellent underscore library:

_.delay = function(func, wait) {
  var args =, 2);
  return setTimeout(function(){ return func.apply(null, args); }, wait);

You can pass as many arguments as you'd like to the function called by setTimeout and as an added bonus (well, usually a bonus) the value of the arguments passed to your function are frozen when you call setTimeout, so if they change value at some point between when setTimeout() is called and when it times out, well... that's not so hideously frustrating anymore :)

Here's a fiddle where you can see what I mean.

As there is a problem with the third optonal parameter in IE and using closures prevents us from changing the variables (in a loop for example) and still achieving the desired result, I suggest the following solution.

We can try using recursion like this:

var i = 0;
var hellos = ["Hello World1!", "Hello World2!", "Hello World3!", "Hello World4!", "Hello World5!"];

if(hellos.length > 0) timeout();

function timeout() {                
    document.write('<p>' + hellos[i] + '<p>');
    if (i < hellos.length)
        setTimeout(timeout, 500);

We need to make sure that nothing else changes these variables and that we write a proper recursion condition to avoid infinite recursion.


IMPORTANT NOTE: While it's most upvoted and accepted, the accepted answer by @staticsan actually is NOT CORRECT! - see David Mulder's comment for explanation why.

Some of the other answers are correct but don't actually illustrate what the problem being solved is, so I created this answer to present that detailed illustration.

As such, I am posting a detailed walk-through of what the browser does and how using setTimeout() helps. It looks longish but is actually very simple and straightforward - I just made it very detailed.

UPDATE: I have made a JSFiddle to live-demonstrate the explanation below: . Many thanks to @ThangChung for helping to kickstart it.

UPDATE2: Just in case JSFiddle web site dies, or deletes the code, I added the code to this answer at the very end.


Imagine a web app with a "do something" button and a result div.

The onClick handler for "do something" button calls a function "LongCalc()", which does 2 things:

  1. Makes a very long calculation (say takes 3 min)

  2. Prints the results of calculation into the result div.

Now, your users start testing this, click "do something" button, and the page sits there doing seemingly nothing for 3 minutes, they get restless, click the button again, wait 1 min, nothing happens, click button again...

The problem is obvious - you want a "Status" DIV, which shows what's going on. Let's see how that works.

So you add a "Status" DIV (initially empty), and modify the onclick handler (function LongCalc()) to do 4 things:

  1. Populate the status "Calculating... may take ~3 minutes" into status DIV

  2. Makes a very long calculation (say takes 3 min)

  3. Prints the results of calculation into the result div.

  4. Populate the status "Calculation done" into status DIV

And, you happily give the app to users to re-test.

They come back to you looking very angry. And explain that when they clicked the button, the Status DIV never got updated with "Calculating..." status!!!

You scratch your head, ask around on (or read docs or google), and realize the problem:

The browser places all its "TODO" tasks (both UI tasks and JavaScript commands) resulting from events into a single queue. And unfortunately, re-drawing the "Status" DIV with the new "Calculating..." value is a separate TODO which goes to the end of the queue!

Here's a breakdown of the events during your user's test, contents of the queue after each event:

  • Queue: [Empty]
  • Event: Click the button. Queue after event: [Execute OnClick handler(lines 1-4)]
  • Event: Execute first line in OnClick handler (e.g. change Status DIV value). Queue after event: [Execute OnClick handler(lines 2-4), re-draw Status DIV with new "Calculating" value]. Please note that while the DOM changes happen instantaneously, to re-draw the corresponding DOM element you need a new event, triggered by the DOM change, that went at the end of the queue.
  • PROBLEM!!! PROBLEM!!! Details explained below.
  • Event: Execute second line in handler (calculation). Queue after: [Execute OnClick handler(lines 3-4), re-draw Status DIV with "Calculating" value].
  • Event: Execute 3rd line in handler (populate result DIV). Queue after: [Execute OnClick handler(line 4), re-draw Status DIV with "Calculating" value, re-draw result DIV with result].
  • Event: Execute 4th line in handler (populate status DIV with "DONE"). Queue: [Execute OnClick handler, re-draw Status DIV with "Calculating" value, re-draw result DIV with result; re-draw Status DIV with "DONE" value].
  • Event: execute implied return from onclick handler sub. We take the "Execute OnClick handler" off the queue and start executing next item on the queue.
  • NOTE: Since we already finished the calculation, 3 minutes already passed for the user. The re-draw event didn't happen yet!!!
  • Event: re-draw Status DIV with "Calculating" value. We do the re-draw and take that off the queue.
  • Event: re-draw Result DIV with result value. We do the re-draw and take that off the queue.
  • Event: re-draw Status DIV with "Done" value. We do the re-draw and take that off the queue. Sharp-eyed viewers might even notice "Status DIV with "Calculating" value flashing for fraction of a microsecond - AFTER THE CALCULATION FINISHED

So, the underlying problem is that the re-draw event for "Status" DIV is placed on the queue at the end, AFTER the "execute line 2" event which takes 3 minutes, so the actual re-draw doesn't happen until AFTER the calculation is done.

To the rescue comes the setTimeout(). How does it help? Because by calling long-executing code via setTimeout, you actually create 2 events: setTimeout execution itself, and (due to 0 timeout), separate queue entry for the code being executed.

So, to fix your problem, you modify your onClick handler to be TWO statements (in a new function or just a block within onClick):

  1. Populate the status "Calculating... may take ~3 minutes" into status DIV

  2. Execute setTimeout() with 0 timeout and a call to LongCalc() function.

    LongCalc() function is almost the same as last time but obviously doesn't have "Calculating..." status DIV update as first step; and instead starts the calculation right away.

So, what does the event sequence and the queue look like now?

  • Queue: [Empty]
  • Event: Click the button. Queue after event: [Execute OnClick handler(status update, setTimeout() call)]
  • Event: Execute first line in OnClick handler (e.g. change Status DIV value). Queue after event: [Execute OnClick handler(which is a setTimeout call), re-draw Status DIV with new "Calculating" value].
  • Event: Execute second line in handler (setTimeout call). Queue after: [re-draw Status DIV with "Calculating" value]. The queue has nothing new in it for 0 more seconds.
  • Event: Alarm from the timeout goes off, 0 seconds later. Queue after: [re-draw Status DIV with "Calculating" value, execute LongCalc (lines 1-3)].
  • Event: re-draw Status DIV with "Calculating" value. Queue after: [execute LongCalc (lines 1-3)]. Please note that this re-draw event might actually happen BEFORE the alarm goes off, which works just as well.
  • ...

Hooray! The Status DIV just got updated to "Calculating..." before the calculation started!!!

Below is the sample code from the JSFiddle illustrating these examples: :

HTML code:

<table border=1>
    <tr><td><button id='do'>Do long calc - bad status!</button></td>
        <td><div id='status'>Not Calculating yet.</div></td>
    <tr><td><button id='do_ok'>Do long calc - good status!</button></td>
        <td><div id='status_ok'>Not Calculating yet.</div></td>

JavaScript code: (Executed on onDomReady and may require jQuery 1.9)

function long_running(status_div) {

    var result = 0;
    // Use 1000/700/300 limits in Chrome, 
    //    300/100/100 in IE8, 
    //    1000/500/200 in FireFox
    // I have no idea why identical runtimes fail on diff browsers.
    for (var i = 0; i < 1000; i++) {
        for (var j = 0; j < 700; j++) {
            for (var k = 0; k < 300; k++) {
                result = result + i + j + k;
    $(status_div).text('calculation done');

// Assign events to buttons
$('#do').on('click', function () {

$('#do_ok').on('click', function () {
    // This works on IE8. Works in Chrome
    // Does NOT work in FireFox 25 with timeout =0 or =1
    // DOES work in FF if you change timeout from 0 to 500
    window.setTimeout(function (){ long_running('#status_ok') }, 0);

javascript parameters callback settimeout