简体   繁体   中英

How to set time function on html web page which carry on itself?

i want to set up time on webpage which goes automatically, so i have html code with id attribute:

 function tellTime() { var now = new Date(); var theHr = now.getHours(); var theMin = now.getMinutes(); document.write("time: " + theHr + ":" + theMin); } document.getElementById("demo").innerHTML = tellTime();
 <div id="demo"></div>

So when the page is reloaded it seems Time but User muss reload page to see the current time.

How can we set up Function, which need not reload to see what is the current time?

 var myVar = setInterval(myTimer, 1000); function myTimer() { var d = new Date(); document.getElementById("demo").innerHTML = d.toLocaleTimeString(); }
 <p>A script on this page starts this clock:</p> <p id="demo"></p> <button onclick="clearInterval(myVar)">Stop time</button>

http://www.w3schools.com/js/tryit.asp?filename=tryjs_setinterval3

Use setInterval() :

function tellTime() 
{
    var now = new Date(),
        hrs = now.getHours(),
        min = now.getMinutes(),
        sec = now.getSeconds();

    document.getElementById("demo").innerHTML = ("time: " + hrs + ":" + min + ':' + sec);
}

window.setInterval(tellTime, 1000);

jsFiddle Demo

You can either refresh it automatically with setTimeout or make an event (click event for example) to reload the time, with setTimeout you can make the time refresh every second like this:

function tellTime() {
    var now = new Date();
    var theHr = now.getHours();
    var theMin = now.getMinutes();
    return "time: " + theHr + ":" + theMin;
}

function printTime() {
    document.getElementById("demo").innerHTML = tellTime();
    setTimeout(printTime, 1000); // Run this function again after a second
}

you need to use setInterval .

 function tellTime() { var now = new Date(); var theHr = now.getHours(); var theMin = now.getMinutes(); var theSec = now.getSeconds(); return "time: " + theHr + ":" + theMin + ":" + theSec; } setInterval(function() { document.getElementById("demo").innerHTML = tellTime(); }, 1000);
 <div id="demo"> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM