How to set up time function update?

When I load this in the browser, it will show the time when the page was fully loaded, but will not refresh every second. How to do it?

var h = date.getHours(); if(h<10) h = "0"+h; var m = date.getMinutes(); if(m<10) m = "0"+m; var s = date.getSeconds(); if(s<10) s = "0"+s; document.write(h + " : " + m + " : " + s); 
+4
source share
2 answers

Use setInterval :

 setInterval(clock, 1000); function clock() { var date = new Date(); var h = date.getHours(); if(h<10) h = "0"+h; var m = date.getMinutes(); if(m<10) m = "0"+m; var s = date.getSeconds(); if(s<10) s = "0"+s; document.write(h + " : " + m + " : " + s); } 

Although you probably want to update the HTML element and not document.write on the page every second.

http://jsfiddle.net/bQNwJ/

+7
source

Wrap it in a function and let it call itself:

 everysecond=1000; // milliseconds function showCurrentTime(){ /*do your timing stuff here */ if(someConditionIsntMet) setTimeout(showCurrentTime, everysecond) } 
0
source

Source: https://habr.com/ru/post/1479126/


All Articles