Amine El were
Amine El were

Reputation: 855

synchronising the Time without reloading the page

I'm building a web app that uses the Time of the computer I found how I can get the hours and the minutes and I succeeded to update them to the UI but the minute field is not synchronised with the time of the computer I have to reload the page to see it updated with the new value, I don't know how to solve this problem I feel like it's a stupid question but really I'm struggling with it, it's my first app with JavaScript so forgive me :p

I tried the setInterval but it didn't work too any help please here is my code:

HTML

<div class="headTime" >Time: <span class="Time"> 03:19</span></div>

Js

    var hours=d.getHours();
    var minutes=d.getMinutes();

    var Time=" 03:19";

    var newTime=Time.replace("03",hours);
    var newTime=newTime.replace("19",minutes);

    setInterval(function(){
  document.querySelector(".Time").innerHTML=newTime;
    },1000);

any better title for the question? I feel it's not accurate

Upvotes: 1

Views: 46

Answers (1)

Maheer Ali
Maheer Ali

Reputation: 36564

You need to get the date each time in callback passed to setInterval. I have added seconds also for test purpose.

You donot need to get the test of span and use replace() and then show. You could directly use Template Strings

`${hours}:${minutes}`

Tip for you is declare the element .Time in global scope and don't call querySelector every second

const span = document.querySelector(".Time");

setInterval(function(){
    let date = new Date();
    let hours = date.getHours();
    let mins = date.getMinutes();
    let seconds = date.getSeconds();
    span.innerHTML= `${hours}:${mins}:${seconds}`;
},1000);
<div class="headTime" >Time: <span class="Time"> 03:19</span></div>

Note:If you are only showing the minutes no seconds you shouldn't call the function every second

Upvotes: 4

Related Questions