为什么 setTimeout 函数会永远执行?

jch*_*and 0 javascript

我阅读了有关计时事件的信息。我很困惑setTimeout:我有一个关于 W3Schools 的例子,它每 500 毫秒运行一次。我读到setTimeout它只工作一次。关联

<head>
  <script>
    function startTime() {
      var today=new Date();
      var h=today.getHours();
      var m=today.getMinutes();
      var s=today.getSeconds();
      document.getElementById('txt').innerHTML=h+":"+m+":"+s;
      setTimeout(function(){startTime()},500);
    }
  </script>
</head>
<body onload="startTime()">
  <div id="txt"></div>
</body>
Run Code Online (Sandbox Code Playgroud)

Poi*_*nty 5

该函数在内部重置定时器:

setTimeout(function(){startTime()},500);
Run Code Online (Sandbox Code Playgroud)

每次运行时,它做的最后一件事就是安排另一次迭代。