Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
like image 981
copenndthagen Avatar asked Sep 01 '15 08:09

copenndthagen


People also ask

How do I pass parameters to setTimeout?

You can pass the parameter to the setTimeout callback function as: setTimeout(function, milliseconds, param1, param2, ...) eg. Yeah!

Is setTimeout a callback function?

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.

What are the two parameters of the setTimeout function?

Developers generally pass only two parameters to setTimeout method — the callback function and the timeout period.


3 Answers

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.

like image 125
Maciej Krawczyk Avatar answered Oct 26 '22 19:10

Maciej Krawczyk


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);
like image 20
Purag Avatar answered Oct 26 '22 19:10

Purag


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.

like image 6
myfavoritenoisemaker Avatar answered Oct 26 '22 17:10

myfavoritenoisemaker