Skip to main content
Bases de Svelte
Introduction
Réactivité
Props
Logique
Events
Bindings
Classes and styles
Actions
Transitions
Advanced Svelte
Advanced reactivity
Reusing content
Motion
Advanced bindings
Advanced transitions
Context API
Special elements
<script module>
Next steps
Basic SvelteKit
Introduction
Routing
Loading data
Headers and cookies
Shared modules
Forms
API routes
$app/state
Errors and redirects
Advanced SvelteKit
Hooks
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion

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>
<script lang="ts">
	import { SvelteDate } from 'svelte/reactivity';

	let date = new SvelteDate();

	// ...
</script>

Modifier cette page sur Github

précédent suivant
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>