<!DOCTYPE html>
<html>
<head>
<title>test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<span id="txt">5</span>
<span>秒倒计时</span>
<script type="text/javascript">
var i = 5;
var tim = function() {
i--;
document.getElementById("txt").innerHTML = i;
setTimeout("tim()", 1000);
};
</script>
</body>
</html>
我实用setInterval成功实现了倒计时,但是为什么用setTimeout不行?我哪里写错了么?
setTimeout()方法只运行一次,当达到设定的时间后就运行指定的代码,运行完后就结束,如果还想再次执行同样的函数,可以在函数体内再次调用setTimeout(),可以达到循环调用的效果。
<script type="text/javascript"> var i = 5; var tim = function() { i--; document.getElementById("txt").innerHTML = i; setTimeout("tim()", 1000); }; setTimeout("tim()", 1000); </script>