将参数传递给setTimeout回调函数

tes*_*dtv 8 javascript jquery settimeout

我有一些JS代码如下;

var x = self.someAJAXResponseJSON; // x has some object value here
setTimeout(function(x){
    console.log("setTimeout ... : " + x); // But x is undefined here
}, 1000);
Run Code Online (Sandbox Code Playgroud)

所以我想将"x"传递给setTimeout回调函数.但我在setTimeout中得到"x"未定义.

我究竟做错了什么 ?

更新

使用DOJO JS修复类似问题的任何想法

setTimeout(dojo.hitch(this, function(){
    this.executeSomeFunction(x); // what shud be this
    console.log("setTimeout ... : " + x); // But x is undefined here
}), 1000);
Run Code Online (Sandbox Code Playgroud)

Mac*_*zyk 11

或者你可以在不创建闭包的情况下完成.

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

window.setTimeout(myFunction, 10, 'hello', 'world');
Run Code Online (Sandbox Code Playgroud)

但请注意,IE < 10 根据MDN,它不起作用.


Pur*_*rag 7

setTimeout调用回调函数,它不传递任何参数(默认); 也就是说,x调用回调时参数未定义。

如果删除参数xx在函数主体中将不会引用未定义的参数,而是引用您在调用外部定义的变量setTimeout()

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

另外,如果它必须是一个参数,则可以将其作为参数传递给setTimeout(帮自己一个忙,并用不同的方式命名):

var x = "hello";
setTimeout(function (y) {
    console.log("setTimeout ... : " + y);
}, 1000, x);
Run Code Online (Sandbox Code Playgroud)


小智 6

我自己遇到了这个并查看了 Node 文档,要传递给函数的参数作为 setTimeout 调用的第 3 个(或更多)参数传入,因此...

myfunc = function(x){console.log(x)};
x = "test";
setTimeout(myfunc,100,x);
Run Code Online (Sandbox Code Playgroud)

为我工作。


moo*_*e99 2

在您的代码中,console.log(x)指的是x回调函数的参数。

只需从函数签名中省略它,就可以了:

setTimeout(function(){
  console.log("setTimeout ... : " + x); // now x is the global x
}, 1000);
Run Code Online (Sandbox Code Playgroud)