'setTimeout function is running infinitely

I read that setTimeout function only runs once and setInterval function runs infinitely. But in this code of digital clock which I picked from w3schools setTimeout is also running infinitely. Is it something to do with the onload method?

<!DOCTYPE html>
<html>

<head>
    <script type="text/javascript">
        function startTime() {
            var today = new Date();
            var h = today.getHours();
            var m = today.getMinutes();
            var s = today.getSeconds();
            m = checkTime(m);
            s = checkTime(s);
            document.getElementById('txt').innerHTML =
                h + ":" + m + ":" + s;
            var t = setTimeout(startTime, 500);
        }

        function checkTime(i) {
            if (i < 10) {
                i = "0" + i
            }; // add zero in front of numbers < 10
            return i;
        }
    </script>
</head>

<body onload="startTime()">
    <div id="txt"></div>
</body>

</html>


Solution 1:[1]

This version of setInterval is running infinitely because the startTime function is a recursive function. A recursive function is a function that calls itself during its execution, which, most of the time, means that the function runs infinitely.

See here:

function startTime() {
  // Code...
  var t = setTimeOut(startTime, 500);
}

The setTimeOut is calling the startTime function, which in turn is calling the setTimeOut function... and it just keeps on going.

Solution 2:[2]

This is a textbook case of recursion - setTimeout() calls startTime(), which calls setTimeout()...which in turn calls startTime() again.

You'll need to break that loop. Simply put, you cannot call startTime() from within startTime() without some path through the function that doesn't call startTime()

Solution 3:[3]

<!DOCTYPE html>
<html>
<body>
  <h2>
    <p id="demo"></p>
    <script>
      const myTimeout = setTimeout(startTime, 1000);

      function startTime() {
        const date = new Date();
        document.getElementById("demo").innerHTML = date.toLocaleTimeString();
        setTimeout(function() {
          startTime()
        }, 1000);
      }
    </script>
</body>
</html>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Take-Some-Bytes
Solution 2 David Miner
Solution 3 ESP