請問實用setTimeout方法為什么不能實現倒計時?
<!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不行?我哪里寫錯了么?
2019-11-05
setTimeout()方法只運行一次,當達到設定的時間后就運行指定的代碼,運行完后就結束,如果還想再次執行同樣的函數,可以在函數體內再次調用setTimeout(),可以達到循環調用的效果。