I have code
function clearPrintNum(sec, minute) {
setTimeout(function() {console.clear(); console.log(`${minute} : ${sec}`);}, sec * 1000);
}
for(var minute = 0; minute < 60; minute++){
for (let second = 0; second < 60; second++) {
clearPrintNum(second, minute);
}
}
Which should return first minute then character ":" and after that seconds.
Problem is that variable minute starts at 59, instead of 0.
I tried using while
function clearPrintNum(sec, minute) {
setTimeout(function() {console.clear(); console.log(`${minute} : ${sec}`);}, sec * 1000);
}
let mins = 0;
while(mins < 60) {
for (let second = 0; second < 60; second++) {
clearPrintNum(second, mins);
}
++mins;
}
and
function clearPrintNum(sec, minute) {
setTimeout(function() {console.clear(); console.log(`${minute} : ${sec}`);}, sec * 1000);
}
var minute = 0;
for(; minute < 60; minute++){
for (let second = 0; second < 60; second++) {
clearPrintNum(second, minute);
}
}
but it doesn’t work.
2
Answers
The loop runs very quickly, which is why you only see 59.
If you remove
console.clear();
, you will see that the values start at 0.Your output will look like this:
No, it starts at 0. You’ve omitted useful debugging information in your use of
console.clear()
. Remove that and you’ll see that every second you log 60 values, from 0 to 59:Which essentially demonstrates that every second you’re logging that second’s value for every minute, all at once.
This is because the
timeout
only accounts for seconds:If you want to account for minutes as well, add that to the calculation:
For example: