Home > OS >  I have Code to get date and time then display it but how do I make it refresh itself in svelte
I have Code to get date and time then display it but how do I make it refresh itself in svelte

Time:07-06

This is my code I get all the info I need but it only updates itself when I refresh the window I want it to update automatically every second

<script>
        const d = new Date();
    
        let date = d.getDate()
        let month = d.getMonth();
        let year = d.getFullYear();
        let hour = d.getHours();
        let minute = d.getMinutes();
        let second = d.getSeconds();
    </script>
    
    <main>
        <div >
            <div >
              <div >
                <h1 >{date}/{month}/{year}</h1>
                <br>
                <h1 >{hour}:{minute}:{second}</h1>
              </div>
            </div>
          </div>
    </main>

CodePudding user response:

You would have to re-assign the variables periodically, e.g. using setInterval, using a new Date each time. Note, that if you use exactly one second as an interval, changes could be missed due to shift/slight delays.

Implementing an accurate and efficient timer is an interesting problem of its own, there is an entire HTTP 203 episode on that. Jake's implementation is this (made signal optional):

export function animationInterval(ms, signal, callback) {
  // Prefer currentTime, as it'll better sync animtions queued in the 
  // same frame, but if it isn't supported, performance.now() is fine.
  const start = document.timeline ? document.timeline.currentTime : performance.now();

  function frame(time) {
    if (signal?.aborted) return;
    callback(time);
    scheduleFrame(time);
  }

  function scheduleFrame(time) {
    const elapsed = time - start;
    const roundedElapsed = Math.round(elapsed / ms) * ms;
    const targetNext = start   roundedElapsed   ms;
    const delay = targetNext - performance.now();
    setTimeout(() => requestAnimationFrame(frame), delay);
  }

  scheduleFrame(start);
}

So it could be used like this:

<script>
    import { animationInterval } from './animation.js';

    let date, month, year, hour, minute, second;
    function update() {
        const d = new Date();
        date = d.getDate()
        month = d.getMonth();
        year = d.getFullYear();
        hour = d.getHours();
        minute = d.getMinutes();
        second = d.getSeconds();
    }
    
    update();
    animationInterval(1000, undefined, update);
</script>

<h1 >{date}/{month}/{year}</h1> <br>
<h1 >{hour}:{minute}:{second}</h1>

REPL

CodePudding user response:

You can use setInterval to execute code. For example, if you want the code to re-execute every 1 second.

function printTime() {
  const date = new Date();
  console.log( date.toString() );
}

//          function    time (in ms)
setInterval(printTime(), 1000);

(Note; StackOverflow's code snippet will only execute setInterval once.)

  • Related