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);
You can pass the parameter to the setTimeout callback function as: setTimeout(function, milliseconds, param1, param2, ...) eg. Yeah!
Introduction to JavaScript setTimeout()cb is a callback function to be executed after the timer expires. delay is the time in milliseconds that the timer should wait before executing the callback function.
Developers generally pass only two parameters to setTimeout method — the callback function and the timeout period.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With