JavaScript - SetInterval计时器无法正常工作

4

我得到了这段脚本(在本地运行):

<script>

last = 0;

function uploadnew(){

var randomnumber=Math.floor(Math.random()*6);
if(randomnumber != last){
    document.forms['f'+randomnumber].submit();
} else { uploadnew(); }

}

setInterval (uploadnew(), 1000*60*5);

</script>

但是看起来setInterval不起作用/发送表单函数不起作用...任何帮助将不胜感激!谢谢!

如果您将表单提交到同一窗口,它将加载一个新页面并停止间隔。 - mplungjan
是的,我知道。我正在将它加载到 iframe 中。 - Paul
4个回答

10

你需要在函数名后面不加括号调用setInterval(),像这样:

setInterval(uploadnew, 1000*60*5);

使用括号会立即调用函数并将结果(undefined)赋给定时器去运行,而不是传递函数本身,因此应该避免使用括号,直接传递函数本身。


5

在setInterval调用中,需要删除uploadnew()后面的()

setInterval (uploadnew, 1000*60*5);

在JavaScript中,函数是一等对象,可以被传递给其他函数。在这个例子中,你想要将函数本身传递给setInterval,而不是先调用它,然后再传递其返回值。
不建议使用setInterval("uploadnew()", 1000*60*5);,因为它是eval的“隐藏”形式。如果没有必要,就不应该使用eval,因为eval是邪恶的。详情请参见Eval is evil and you shouldn't use it if you don't have to.

4
你需要传递函数的引用而不是直接调用它。
这样做:
setInterval (uploadnew(), 1000*60*5);

should be:

setInterval (uploadnew, 1000*60*5);

如果按照原样呼叫,你需要让 uploadnew() 函数返回一个可传递给 setInterval 的函数。
function uploadnew() {
    return function(){
        var randomnumber=Math.floor(Math.random()*6);
        if(randomnumber != last) {
            document.forms['f'+randomnumber].submit();
        } else { uploadnew()(); }
    }
}

注意递归调用的变化。

2
使用
setTimeout ( expression, timeout );

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接