Pass parameter to setTimeout callback function

I have 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 get "x" as undefined inside setTimeout.

What am I doing wrong?

UPDATED

Any fix idea for a similar problem 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);
+4
source share
5 answers

Alternatively, you can do this without creating a closure.

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

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

But note that this does not work IE < 10 according to MDN .

+5
source

setTimeout , ( ); x undefined .

x, x undefined, , setTimeout().

var x = "hello";
setTimeout(function () { //note: no 'x' parameter
    console.log("setTimeout ... : " + x);
}, 1000);

, , setTimeout ( ):

var x = "hello";
setTimeout(function (y) {
    console.log("setTimeout ... : " + y);
}, 1000, x);
+4

console.log(x) x .

, :

setTimeout(function(){
  console.log("setTimeout ... : " + x); // now x is the global x
}, 1000);
+2

, , : undefined.

, x:

var x = self.someAJAXResponseJSON; // x has some object value here
setTimeout((function(y){
    return(function() {
        console.log("setTimeout ... : " + y);
    })
})(x), 1000);
+1
source

The setTimeout method is designed to accept a function or a piece of code as the first argument, but in case you accepted an anonymous function with the parameter x and which is called without taking any arguments, therefore it shows undefined because there is no specific function that takes x . What you can do is first define the function you want to call, and then just call it in the setTimeout method. See the following code snippet:

var x = self.someAJAXResponseJSON;
function mylog(x){
  console.log("setTimeout ... : " + x);
}
setTimeOut(mylog(x),1000);
+1
source

All Articles