how to update time regularly?

后端 未结 10 850
再見小時候
再見小時候 2020-12-03 02:11
function timeClock()
{
    setTimeout(\"timeClock()\", 1000);        
    now = new Date();
    alert(now);
    f_date = now.getDate()+\" \"+strMonth(now.getMonth())         


        
相关标签:
10条回答
  • 2020-12-03 02:34

    There may be something in timeago jQuery plugin you can hook into, but I haven't honestly tried...

    http://timeago.yarp.com/

    0 讨论(0)
  • 2020-12-03 02:35

    There are a number of mistakes in your code. Without the use of var infront of your variable declarations, you leak them into the global scope.

    Also, the use of document.write is discouraged.

    Here's how I would do it:

    JavaScript:

    function updateClock() {
        var now = new Date(), // current date
            months = ['January', 'February', '...']; // you get the idea
            time = now.getHours() + ':' + now.getMinutes(), // again, you get the idea
    
            // a cleaner way than string concatenation
            date = [now.getDate(), 
                    months[now.getMonth()],
                    now.getFullYear()].join(' ');
    
        // set the content of the element with the ID time to the formatted string
        document.getElementById('time').innerHTML = [date, time].join(' / ');
    
        // call this function again in 1000ms
        setTimeout(updateClock, 1000);
    }
    updateClock(); // initial call
    

    HTML:

    <div id="time"> </div>
    
    0 讨论(0)
  • 2020-12-03 02:43

    setInterval(expression, timeout);

    The function setTimeout is intended for a single timeout, so using setInterval would be a more appropriate option. SetInterval will run regularly without the additional lines that Ivo's answer has.

    I would rewrite Ivo's answer as follows:

    JavaScript:

    function updateClock() {
      // Ivo's content to create the date.
      document.getElementById('time').innerHTML = [date, time].join(' / ')
    }
    setInterval(updateClock, 1000);
    

    Try it out yourself! https://jsfiddle.net/avotre/rtuna4x7/2/

    0 讨论(0)
  • 2020-12-03 02:46

    I think your setTmeout function has the wrong variables, the first one should be a function not a string, that confused me for a bit. Basically you need to write to the span tag when you run the function.

    I created a jQuery version in a fiddle to demonstrate what I mean. Didn't have your strMonth function but you get the idea. I also changed the alert to console.log but you can remove that line.

    http://jsfiddle.net/5JWEV/

    0 讨论(0)
提交回复
热议问题