+ 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

8th Mar 2022, 4:03 PM
ChigozirimAngela (Not My Name).
8 Respostas
+ 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..
8th Mar 2022, 4:10 PM
Jayakrishna 🇼🇳
+ 3
Jayakrishna🇼🇳, small correction: "1 sec".
8th Mar 2022, 4:38 PM
Solo
Solo - avatar
+ 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);
8th Mar 2022, 10:37 PM
Solo
Solo - avatar
+ 2
Everything becomes clear if you remove the variables â˜ș: function timer(){ document.getElementById("timer"). innerHTML = new Date().getMinutes() +" : "+new Date().getSeconds(); } setInterval(timer, 1000);
8th Mar 2022, 4:36 PM
Solo
Solo - avatar
+ 1
Yes. I mean 1000milliseconds actually.. I edited it. 1000ms = 1 sec Solo thanks for your feedback..
8th Mar 2022, 4:42 PM
Jayakrishna 🇼🇳
8th Mar 2022, 4:49 PM
ChigozirimAngela (Not My Name).
8th Mar 2022, 4:55 PM
Jayakrishna 🇼🇳