setTimeout does not work

孤街浪徒 提交于 2019-12-21 17:31:36

问题


I want to load an OWL file before executing other (visualisation-)scripts. To do this I tried everything from

$(document).ready

to

function visualize (file) {
if (!file)
    {setTimeout(visualize(file), 2000)}
else
    {jQuery(function($){visFeaturePool.init(file)})}}

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:


Instead of

// #1
setTimeout(visualize(file), 2000);

you want

// #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);

Those three explained:

  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.

(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.)




回答2:


setTimeout(visualize(file), 2000) calls visualize immediately and passes its result to setTimeout, just like any other function call.




回答3:


Try this:

function visualize (file) {
  if (!file)
    {setTimeout(function(){visualize(file);}, 2000)}
  else
    {jQuery(function($){visFeaturePool.init(file)})}}

This way you are giving setTimeout an anonymous function that will be executed when scheduled, and you can pass parameters to visualize using a closure like file.




回答4:


setTimeout(visualize, 2000, file);

will also work.



来源:https://stackoverflow.com/questions/8375962/settimeout-does-not-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!