3

我想要一个 JavaScript 函数在页面加载后 60 秒运行。经过一番研究,我发现 setTimeout() 是解决方案。

所以这就是我所做的:

<body onLoad="setTimeout(postAction('news.reads', 'article'), 60000);">

不知何故, setTimeout 不起作用。页面加载后,无需等待 60 秒,因为 postAction() 会立即运行。

为什么会这样?如何解决?那里有 setTimeout() 的替代品吗?谢谢!

4

4 回答 4

11

You need to wrap postAction in a function to defer execution:

setTimeout(function() { postAction('news.reads', 'article'); }, 60000);

You are actually executing postAction immediately, your code is equivalent to:

var result = postAction('news.reads', 'article');

setTimeout(result, 60000);
于 2012-11-06T22:25:49.597 回答
0

您是否使用setTimeout类似:

setTimeout(function(){alert("OK");}, 1000 * 60); // alert "OK" in 60s
于 2012-11-06T22:16:09.267 回答
0

在 JS 中做你想做的事情的正确方法,即在页面加载后设置超时:

(function(w)
{
    var load = function()
    {
         setTimeout(postAction,60000);
         if (w.removeEventListener)
         {//remove listeners, to avoid leak...
             return w.removeEventListener('load',load,false);
         }
         return w.attachEvent('onload',load);
    };
    if (w.addEventListener)
    {
        return w.addEventListener('load',load,false);
    }
    return w.attachEvent('onload',load);
}(this));

而不是window.onload = function(){setTimeout(postAction,60000);};, 这也可以,但会导致 IE <9 中的内存泄漏。那只是为了完整起见
无论如何,这里的关键是setTimeout(postAction,60000);

Update
After seeing the code you're using, this is the easiest fix:

<body onLoad="setTimeout(function(){ return postAction('news.reads', 'article');}, 60000);">
于 2012-11-06T22:23:12.710 回答
-2
<script>
        function doSomeJavascript() {
            // javascript code goes here
           alert('5 secs is up!');
        }
        // calls function doSomeJavascript() 5 secs after page load
        var interval = setInterval(doSomeJavascript, 5000);

        setTimeout(function() {
           window.clearInterval(interval);
        }, 5000);
</script>
于 2012-11-06T22:16:57.860 回答