I am trying to understand Math.max(timeLeft/1000,0); returning its maximum value as 0. I did a lot of research as a noob. I read the w3schools's tutorial about Math and all its methods. However the value returning 0 is really confusing me. The full code is below.
var start = document.getElementById("start");
var dis = document.getElementById("display");
var finishTime;
var timerLength = 10;
var timeoutID;
dis.innerHTML = "Time Left: " + timerLength;
if(localStorage.getItem('myTime')){ Update();
}
start.onclick = function () { localStorage.setItem('myTime', ((new Date()).getTime() + timerLength * 1000)); if (timeoutID != undefined) window.clearTimeout(timeoutID); Update();
}
function Update() { finishTime = localStorage.getItem('myTime'); var timeLeft = (finishTime - new Date()); dis.innerHTML = "Time Left: " + Math.max(timeLeft/1000,0); timeoutID = window.setTimeout(Update, 100);
}Also why is window.setTimeout(Update, 100); behaving as setInterval in this code?
The full working code is here
Note: I read this article and I'm trying to understand how localstorage is working with the date function.
Another note: There is nothing wrong with the code above. It is working as it should. I am just trying to understand a certain piece of code, which is really confusing. I now understand why it is returning as 0.
3 Answers
timeLeft is negative, so 0 is the max value.
Math.max(timeLeft/1000, 0) return 0 when timeLeft is non-positive number.
window.setTimeout(Update, 100) is behaving as setInterval is that it call itself in loop every 100 just as the setInterval.
Actually Math.max does not always returns zero, otherwise you would always see "0" in the display span. It returns zero only when new Date() becomes greater than finishTime (after timerLength * 1000 ms = 10 * 1000 ms = 10 s).
About setTimeout, considering the following code, f calls setTimeout, which calls f after 1 sec, which calls setTimeout, and so on :
function f () { setTimeout(f, 1000);
}The result is similar to setInterval but not exactly the same. Read the following article to know why (author : jQuery's father himself) : .
var start = document.getElementById("start");
var dis = document.getElementById("display");
var finishTime;
var timerLength = 10;
var timeoutID;
var fakeStorage = (new Date()).getTime() + timerLength * 1000;
dis.innerHTML = "Time Left: " + timerLength;
if(fakeStorage){ Update();
}
start.onclick = function () { fakeStorage = ((new Date()).getTime() + timerLength * 1000); if (timeoutID != undefined) window.clearTimeout(timeoutID); Update();
}
function Update() { finishTime = fakeStorage; var timeLeft = (finishTime - new Date()); dis.innerHTML = "Time Left: " + Math.max(timeLeft/1000,0); timeoutID = window.setTimeout(Update, 100);
}<button type="button">start</button>
<span></span> 1