setTimeout不起作用 [英] setTimeout does not work

查看:129
本文介绍了setTimeout不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在执行其他(可视化)脚本之前加载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);

这三个解释:

  1. (如SLaks所述)此方法立即调用visualize ,然后将其返回值传递到setTimeout(由于visualize自身进行了调用,因此它不断递归地进行调用,最终导致并出现堆栈溢出错误).
  2. 这会将函数引用传递到setTimeout中,该函数引用在被调用时将调用visualize并将其传递给file参数.即使您的代码已运行并返回,我们传递给setTimeout的函数仍可以访问file参数,因为该函数是创建时上下文的 closure ,其中包括file.更多: 关闭并不复杂
  3. 这会将visualize函数引用传递到setTimeout(请注意,后面没有()(file)),还将file传递给setTimeout(在延迟之后).在现代的浏览器中,setTimeout会在以后调用它时将其传递给该函数.
  1. (As SLaks mentions) This calls visualize immediately, and then passes its return value into setTimeout (and since visualize calls itself, it keeps calling itself recursively and you end up with a stack overflow error).
  2. This passes a function reference into setTimeout that, when called, will call visualize and pass it the file argument. The function we're passing into setTimeout will have access to the file argument, even though your code has run and returned, because that function is a closure over the context in which it was created, which includes file. More: Closures are not complicated
  3. This passes the visualize function reference into setTimeout (note we don't have () or (file) after it) and also passes file into setTimeout (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屋!

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