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>