Ermac Ermac - 6 months ago 12
Javascript Question

JavaScript clock not showing current time on mobile devices

I got this JavaScript Code to display the current time on my website, works perfectly for desktop but it doesn't work on mobile devices

It freezes on the time when the user visits the page

Is it any way to make this possible? Something like refresh the script every sec to show the current time or any other solution?



document.getElementById("clock").innerHTML = GetTime();

function GetTime(){
var d = new Date();
var nhour = d.getHours(),nmin=d.getMinutes();
if (nmin<=9) {
nmin = "0" + nmin
}
return nhour+":"+nmin+"";
}

<span id="clock"></span>





Your help is really appreciated!

EDIT: Thanks to mdickin I realized the clock doesn't update even in desktop. So the entire code has something wrong.

Answer

Use setInterval to run your GetTime() function every second:

document.getElementById("clock").innerHTML = GetTime();

function GetTime(){
        var d = new Date();
        var nhour = d.getHours(),nmin=d.getMinutes();
        if (nmin<=9) { 
            nmin = "0" + nmin 
        }
        return nhour+":"+nmin+"";
    }
    
    setInterval(GetTime, 1000); // run GetTime every 1000ms
<span id="clock"></span>