Global variable is logged as undefined when passed as parameter to setTimeout callback function
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.
When setTimeout
invokes the callback, it doesn't pass any arguments (by default); that is, the argument x
is undefined when the callback is invoked.
If you remove the parameter x
, x
in the function body won't refer to the undefined parameter but instead to the variable you defined outside the call to setTimeout()
.
var x = "hello";setTimeout(function () { //note: no 'x' parameter console.log("setTimeout ... : " + x);}, 1000);
Alternatively, if it must be a parameter, you can pass it as an argument to setTimeout
(do yourself a favor and name it differently, though):
var x = "hello";setTimeout(function (y) { console.log("setTimeout ... : " + y);}, 1000, x);
Ran into this myself and looked at the Node docs, arguments to be passed into the function come in as a 3rd(or more) parameter to the setTimeout call so...
myfunc = function(x){console.log(x)};x = "test";setTimeout(myfunc,100,x);
Worked for me.