Herschelle
Herschelle

Reputation: 27

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>

Upvotes: 0

Views: 120

Answers (3)

ESP
ESP

Reputation: 11

<!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>

Upvotes: 0

Take-Some-Bytes
Take-Some-Bytes

Reputation: 952

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.

Upvotes: 0

David Miner
David Miner

Reputation: 318

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()

Upvotes: 1

Related Questions