+ 2
Output different when date variable is assigned a value outside the function.
Why is the time updated and printed every second when the variable date is assigned the date object inside the function(see code labeled second timer)? Why does the time only update when the page is reloaded for the date variable assigned outside the function?(see code labelled first timer). https://code.sololearn.com/W06i38bVFjNP/?ref=app
8 Answers
+ 3
There setInterval() call timer method after every 1000 milliseconds = 1sec.. So timer1 acting outside date variable which is assigned it's value before function and not getting updated on function calls but timer2 assigns new value in every new function call so its upadating every 1000ms.
that's the purpose of setInterval mainly... without setInterval, both functions works same..
+ 3
Jayakrishna🇮🇳, small correction: "1 sec".
+ 3
FF9900, you are wrong.
The problem is in the field of view. You just declared a global date variable for the timer() function. Here's what your example would look like correctly, but with the global time variable:
function timer() {
document.getElementById("timer").
innerHTML = time;
}
function timer2() {
document.getElementById("timer2").
innerHTML = time;
}
function runAll() {
let
date = new Date(),
mins = date.getMinutes(),
secs = date.getSeconds();
time = mins + " : " + secs;
timer();
timer2();
}
setInterval(runAll, 1000);
+ 2
Everything becomes clear if you remove the variables ☺️:
function timer(){
document.getElementById("timer").
innerHTML = new Date().getMinutes()
+" : "+new Date().getSeconds();
}
setInterval(timer, 1000);
+ 1
Yes. I mean 1000milliseconds actually..
I edited it.
1000ms = 1 sec
Solo thanks for your feedback..
+ 1
Jayakrishna🇮🇳 Thank you!
+ 1
You're welcome. ChigozirimAngela (Not My Name).