Svelte ships with several reactive classes that you can use in place of JavaScript built-in objects — namely Map
, Set
, Date
, URL
and URLSearchParams
.
In this exercise, we could declare date
using $state(new Date())
and reassign it inside the setInterval
. But a nicer alternative is to use SvelteDate
from svelte/reactivity
:
App
<script>
import { SvelteDate } from 'svelte/reactivity';
let date = new SvelteDate();
// ...
</script>
previous next
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<script>
let date = new Date();
const pad = (n) => n < 10 ? '0' + n : n;
$effect(() => {
const interval = setInterval(() => {
date.setTime(Date.now());
}, 1000);
return () => {
clearInterval(interval);
};
});
</script>
<p>The time is {date.getHours()}:{pad(date.getMinutes())}:{pad(date.getSeconds())}</p>