setTimeout不起作用 [英] setTimeout does not work
问题描述
我想在执行其他(可视化)脚本之前加载OWL文件.为此,我尝试了
I want to load an OWL file before executing other (visualisation-)scripts. To do this I tried everything from
$(document).ready
到
function visualize (file) {
if (!file)
{setTimeout(visualize(file), 2000)}
else
{jQuery(function($){visFeaturePool.init(file)})}}
我认为setTimeout必须有可能,但这是行不通的.我抛出错误: Uncaught RangeError:超出了最大调用堆栈大小,因此它不会等待,它只是调用可视化函数,直到堆栈已满为止.
I think it has to be possible with the setTimeout but that isn't working. I throws the error: Uncaught RangeError: Maximum call stack size exceeded, so it doesn't wait, it just recalls the visualize function untill the stack is full.
有人知道我在做什么错吗? 谢谢!
Does anybody know what I am doing wrong? Thanks!
推荐答案
代替
// #1
setTimeout(visualize(file), 2000);
您想要的
// #2
setTimeout(function() {
visualize(file);
}, 2000);
或在现代浏览器上,您可以提供在延迟后传递给函数的参数:
or on modern browsers, you can provide arguments to pass to the function after the delay:
// #3
setTimeout(visualize, 2000, file);
这三个解释:
- (如SLaks所述)此方法立即调用
visualize
,然后将其返回值传递到setTimeout
(由于visualize
自身进行了调用,因此它不断递归地进行调用,最终导致并出现堆栈溢出错误). - 这会将函数引用传递到
setTimeout
中,该函数引用在被调用时将调用visualize
并将其传递给file
参数.即使您的代码已运行并返回,我们传递给setTimeout
的函数仍可以访问file
参数,因为该函数是创建时上下文的 closure ,其中包括file
.更多: 关闭并不复杂 - 这会将
visualize
函数引用传递到setTimeout
(请注意,后面没有()
或(file)
),还将file
传递给setTimeout
(在延迟之后).在现代的浏览器中,setTimeout
会在以后调用它时将其传递给该函数.
- (As SLaks mentions) This calls
visualize
immediately, and then passes its return value intosetTimeout
(and sincevisualize
calls itself, it keeps calling itself recursively and you end up with a stack overflow error). - This passes a function reference into
setTimeout
that, when called, will callvisualize
and pass it thefile
argument. The function we're passing intosetTimeout
will have access to thefile
argument, even though your code has run and returned, because that function is a closure over the context in which it was created, which includesfile
. More: Closures are not complicated - This passes the
visualize
function reference intosetTimeout
(note we don't have()
or(file)
after it) and also passesfile
intosetTimeout
(after the delay). On modern browsers,setTimeout
will pass that on to the function when calling it later.
(#2和#3之间有一个重要区别:对于#2,如果在调用setTimeout
的时间和计时器到期之间更改了file
,则visualize
将看到file
的新值.不过,使用#3不会.两者都有其用途.)
(There's an important difference between #2 and #3: With #2, if file
is changed between when setTimeout
is called and the timer expires, visualize
will see file
's new value. With #3, though, it won't. Both have their uses.)
这篇关于setTimeout不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!