我有代码获得日期和时间,然后显示它,但是如何使其在Svelte中刷新本身

发布于 2025-02-13 04:06:02 字数 803 浏览 2 评论 0原文

这是我的代码 我获取我需要的所有信息

<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 class="hero min-h-screen bg-base-200">
            <div class="hero-content text-center">
              <div class="max-w-md">
                <h1 class="text-8xl font-bold">{date}/{month}/{year}</h1>
                <br>
                <h1 class="text-8xl font-bold">{hour}:{minute}:{second}</h1>
              </div>
            </div>
          </div>
    </main>

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 class="hero min-h-screen bg-base-200">
            <div class="hero-content text-center">
              <div class="max-w-md">
                <h1 class="text-8xl font-bold">{date}/{month}/{year}</h1>
                <br>
                <h1 class="text-8xl font-bold">{hour}:{minute}:{second}</h1>
              </div>
            </div>
          </div>
    </main>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

无风消散 2025-02-20 04:06:02

您必须定期使用setInterval,每次使用setInterval进行定期重新分配变量。请注意,如果您完全使用一秒钟作为间隔,则由于班次/轻微的延迟,可能会错过更改。

实现准确有效的计时器是一个有趣的问题,它本身就是一个。杰克的实现是此(制作信号可选):

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);
}

因此可以像这样使用:

<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 class="text-8xl font-bold">{date}/{month}/{year}</h1> <br>
<h1 class="text-8xl font-bold">{hour}:{minute}:{second}</h1>

repl

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 class="text-8xl font-bold">{date}/{month}/{year}</h1> <br>
<h1 class="text-8xl font-bold">{hour}:{minute}:{second}</h1>

REPL

甜是你 2025-02-20 04:06:02

您可以使用 setInterval 执行代码。例如,如果您希望代码每1秒重新执行一次。

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

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

(注意; Stackoverflow的代码片段只能执行SetInterval一次。)

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.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文