我有代码获得日期和时间,然后显示它,但是如何使其在Svelte中刷新本身
这是我的代码 我获取我需要的所有信息
<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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须定期使用
setInterval
,每次使用setInterval
进行定期重新分配变量。请注意,如果您完全使用一秒钟作为间隔,则由于班次/轻微的延迟,可能会错过更改。实现准确有效的计时器是一个有趣的问题,它本身就是一个那。杰克的实现是此(制作
信号
可选):因此可以像这样使用:
repl
You would have to re-assign the variables periodically, e.g. using
setInterval
, using a newDate
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):So it could be used like this:
REPL
您可以使用 setInterval 执行代码。例如,如果您希望代码每1秒重新执行一次。
(注意; Stackoverflow的代码片段只能执行SetInterval一次。)
You can use setInterval to execute code. For example, if you want the code to re-execute every 1 second.
(Note; StackOverflow's code snippet will only execute setInterval once.)