I dont understand logic behind these if statements

I found this code in one of my pdf files from college, its about a timer with functions to start timer, stop and reset timer. I understand how it all works but one part of code is bugging me.

What is exactly if(timerID) checking for here? I tried checking with console log but it prints 1 then 2 then 3 etc… each time function updateTime calls its self every 1second interval. But im curious what does that if do exactly? It sets clearTime but why? And why does it set timerID to 0 again? What is exactly happening here in that if condition? I know if conditions return true or false but why does it check only value of timerID, what is logic behind it?

And also im curious about

if (!tStart) {
        tStart = new Date();
}

why does if check here for false null value of tStart and if that condition is true it creates new Date object?

Here is code

var timerID = 0;
var tStart = null;

function UpdateTime() {
    if (timerID) {
        console.log(timerID);
        clearTimeout(timerID);
        timerID = 0;
    }
    if (!tStart) {
        tStart = new Date();

    }
    var tDate = new Date();
    var tDiff = tDate.getTime() - tStart.getTime();
    tDate.setTime(tDiff);
    document.theTimer.theTime.value = "" + tDate.getMinutes() + ":" + tDate.getSeconds();
    timerID = setTimeout("UpdateTime()", 1000);
}

function Start() {
    tStart = new Date();
    document.theTimer.theTime.value = "00:00";
    timerID = setTimeout("UpdateTime()", 1000);
}

function Stop() {
    if (timerID) {
        console.log(timerID);
        clearTimeout(timerID);
        timerID = 0;
    }
}

function Reset() {
    tStart = null;
    document.theTimer.theTime.value = "00:00";
}
type or paste code here

HTML:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body onload="Reset()" onunload="Stop()">

    <form name="theTimer">
        <table>
            <tr>
                <td colspan="3" align="center">
                    <input type="text" name="theTime" size="5">
                </td>
            </tr>
            <tr>
                <td></td>
            </tr>
            <tr>
                <td>
                    <input type="button" name="start" value="Start" onclick="Start()">
                </td>
                <td>
                    <input type="button" name="stop" value="Stop" onclick="Stop()">
                </td>
                <td>
                    <input type="button" name="reset" value="Reset" onclick="Reset()">
                </td>
            </tr>
        </table>
    </form>
    <script src="script.js"></script>
</body>

</html>

Hi @Bego96

Let me attempt to answer your question the way I understood it and from what I make out of the code snippet above.

Invoking setTimeout returns a numeric id which you can use for cancelling the timer using clearTimeout. According to this stackOvrflow question, the id is an integer greater than zero. The top voted answer to the linked SO question has a link to the specification which you can also peruse through.

From what I have seen, the author of the code initialized the timerID variable to 0 probably because the setTimeout id will always be an integer greater than 0. If it is not 0, that means a timer was scheduled previously. Further down in the UpdateTime and Start functions, the author assigned the timerID variable to the setTimeout id. If the first scheduled timer expires after 1000ms, the runtime invokes the UpdateTime function but it first clears the previous timer(in case it is still running) by calling clearTimeout and passing the id if the timerID is not 0.

But why clear the previous setTimeout before scheduling another timer? My guess is to ensure the user can click start even when the timer is running. Comment out the if block where the timer is being cleared and click the start button when the timer is still running. You will notice a different behavior.

In my opinion, the problem seems better solved using setInterval but probably there is a reason for using setTimeout.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.