将参数传递给 setTimeout 回调函数 [英] Pass parameter to setTimeout callback function

查看:93
本文介绍了将参数传递给 setTimeout 回调函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些JS代码如下;

var x = self.someAJAXResponseJSON;//x 在这里有一些对象值设置超时(函数(x){console.log("setTimeout ... : " + x);//但是这里 x 是未定义的}, 1000);

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

我做错了什么?

更新

使用 DOJO JS 解决类似问题的任何想法

setTimeout(dojo.hitch(this, function(){this.executeSomeFunction(x);//这应该是什么console.log("setTimeout ... : " + x);//但是这里 x 是未定义的}), 1000);

解决方案

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

function myFunction(str1, str2) {警报(str1);//你好警报(str2);//世界}window.setTimeout(myFunction, 10, 'hello', 'world');

但请注意它不适用于 IE <10 根据 MDN.>

I have some JS code as below;

var x = self.someAJAXResponseJSON; // x has some object value here
setTimeout(function(x){
    console.log("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 ?

UPDATED

Any idea of fix for similar issue using DOJO JS

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

解决方案

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.

这篇关于将参数传递给 setTimeout 回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆