简体   繁体   English

试图为函数和passvariable设置timeout - 不起作用

[英]Trying to settimeout for a function and passvariable - doesn't work

Basically I have a function that passes this... I need this function to be executed 1/3 seconds after a button got clicked so what I thought of doing is: 基本上我有一个通过这个功能...我需要这个功能在点击一个按钮后1/3秒执行所以我想做的是:

setTimeout("somefunction(this)", 3000);

As I know that setTimeout("", x); 我知道setTimeout(“”,x); works with "" but it doesn't work. 使用“”但它不起作用。

I've tried without the "" and it wont work either I tried to: 我试过没有“”它也不会工作要么我试图:

  setTimeout("somefunction("+this+")", 3000);

and still won't work. 并且仍然无法工作。 Did like an hour of attempts at this. 就像一小时的尝试一样。

Any help would be highly appreciated. 任何帮助将受到高度赞赏。

You need to use a closure 你需要使用一个闭包

var that = this;
setTimeout( function(){ somefunction(that); }, 3000);

timeouts are asynchronous events and so the context is lost. 超时是异步事件,因此上下文丢失。 One way to preserve it is to bind it via an immediately-executed function. 保留它的一种方法是通过立即执行的函数绑定它。

setTimeout((function(that) {
    return function() { somefunction(that); };
})(this), 3000);

Another way would be to make a reference to the outer scope in a variable, as @epascarello's answer shows. 另一种方法是在变量中引用外部范围,如@ epascarello的答案所示。

It is always better to pass function references to setTimeout and setInterval than strings, because the latter are evaluated, and eval'ing is evil. 将函数引用传递给setTimeoutsetInterval总是比字符串更好,因为后者是被评估的,并且eval'ing是邪恶的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM