我是JavaScript新手,似乎无法通过setTimeout命令执行任何操作。我知道之前已经多次询问过这个问题了,但过去两个小时我一直在研究以前的所有案例,但它仍然不适合我。这就是我现在所拥有的:
<html>
<script type="text/javascript">
var i = 0;
function aloop() {
document.write(i);
i++;
}
function afunction() {
if (i <= 12) {
setTimeout(aloop(), 1000);
afunction();
}
}
</script>
<form>
<input type=submit value="Click me!" onClick="afunction()">
</html>
任何人都可以告诉我应该怎样做才能使这项工作?
答案 0 :(得分:4)
将函数传递给setTimeout
,而不是函数调用的返回值。
setTimeout(aloop,1000);
答案 1 :(得分:1)
问题是你是调用你的函数而不是排队你的函数。
setTimeout(aloop, 1000)
不 setTimeout(aloop(), 1000);
答案 2 :(得分:1)
你没有描述什么不起作用,但我假设你希望以1000毫秒的间隔写出i
。
这样做:
<html>
<!-- you're missing your head tags -->
<head>
<title> my page </title>
<script type="text/javascript">
var i=0;
function aloop() {
// don't use document.write after the DOM is loaded
document.body.innerHTML = i;
i++;
afunction(); // do the next call here
}
function afunction() {
if (i<=12) {
// v---pass the function, don't call
setTimeout(aloop,1000);
// afunction(); // remove this because it'll call it immediately
}
}
</script>
</head>
<!-- you're missing your body tags -->
<body>
<form>
<input type=submit value="Click me!" onClick="afunction()">
</form> <!-- you're missing your closing form tag -->
</body>
</html>