Javascript clock does not update

Asked

Viewed 159 times

2

I am creating a view that will show the time of a network server and I am using JS to get the current date and time of the server, which by chance diverges with the current time, being in some situations delayed a few minutes.

To display a clock on the screen and keep it up to date, I used the script below:

<script>
	 setInterval(geraIntervalo, 1000);
	 function geraIntervalo() {
	     var d = new Date(), displayDate;                              
	     document.getElementById("horaServidor").innerHTML = d.toLocaleTimeString('pt-BR');
	 }              
</script>

<h3 id="horaServidor"></h3>

However, if when declaring and instantiating the date variable passing values simulating the time received from the server late, the script cannot keep the time updating.

Below is an example:

<script>
	 setInterval(geraIntervalo, 1000);
	 function geraIntervalo() {
	     var d = new Date(2019, 01, 30, 03, 14, 15), displayDate;                             
	     document.getElementById("horaServidor").innerHTML = d.toLocaleTimeString('pt-BR');
	 }              
</script>

<h3 id="horaServidor"></h3>

I didn’t understand why the clock with a late time was prevented from keeping up to date on the screen. Could you help me? I sought some questions and had nothing like the result of my searches made.

Thank you!!

  • 1

    The new Date() will always pick up the current date/time of the system when the function is called by the range. When setting fixed values, the date/time will always be the same.

1 answer

5


When defining fixed values on the object Date() within the function, the values will always be the same. Already the Date() no values, will return the updated system date.

What you can do is declare the object outside the function, and within it increment 1 second with the method .setSeconds(), but I suggest using a more specific name for the variable and not just d, since it will be a variable with a global scope (in this case, I put relogio):

setInterval(geraIntervalo, 1000);
var relogio = new Date(2019, 01, 30, 03, 14, 15), displayDate;
function geraIntervalo() {
   relogio.setSeconds(relogio.getSeconds() + 1);
   document.getElementById("horaServidor").innerHTML = relogio.toLocaleTimeString('pt-BR');
}
<h3 id="horaServidor"></h3>

  • Correct Sam, I hadn’t thought of it that way. Thank you very much, it was exactly what I needed!!

  • 1

    @Theotonio, if you’ve solved your problem, mark the answer as correct. Because then it will help those who have similar doubts to yours and also enable other answers to be drawn up on the basis of what Sam answered.

  • @Augustovasques Done! Thanks Augusto.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.