Global variable is logged as undefined when passed as parameter to setTimeout callback function

javascript, parameters, settimeout, shadowing

Solution

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.

Problem

I have some JS code as below: ``` var x = self.someAJAXResponseJSON; // x has some object value here. setTimeout(function(x){ console.log("In 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? Any idea how to fix a similar issue using Dojo.js? ``` setTimeout(dojo.hitch(this, function(){ this.executeSomeFunction(x); // What should this be? console.log("In setTimeout:", x); // But x is undefined here }), 1000); ```

Original source

Related problems