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!!
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.– Sam