Pass parameter to setTimeout callback function

testndtv picture testndtv · Sep 1, 2015 · Viewed 34k times · Source

I have some JS code as below;

var x = self.someAJAXResponseJSON; // x has some object value here
setTimeout(function(x){
    console.log("setTimeout ... : " + x); // But x is undefined here
}, 1000);

So I want to pass "x" to the setTimeout callback function. But I am getting "x" as undefined inside the setTimeout.

What am I doing wrong ?

UPDATED

Any idea of fix for similar issue using DOJO JS

setTimeout(dojo.hitch(this, function(){
    this.executeSomeFunction(x); // what shud be this
    console.log("setTimeout ... : " + x); // But x is undefined here
}), 1000);

Answer

Maciej Krawczyk picture Maciej Krawczyk · Sep 1, 2015

Alternatively you can do it without creating a closure.

function myFunction(str1, str2) {
  alert(str1); //hello
  alert(str2); //world
}

window.setTimeout(myFunction, 10, 'hello', 'world');

But note it doesn't work on IE < 10 according to MDN.