javascript / intermediate
Snippet
Synchronizing with the DOM using Tick
In Svelte, state updates aren't applied to the DOM immediately but are batched. The 'tick' function returns a promise that resolves as soon as any pending state changes have been applied, which is crucial for logic that depends on the updated DOM.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { tick } from 'svelte';let message = 'Original';let element;async function updateMessage() {message = 'Updated Content';console.log(element.textContent); // Still 'Original'await tick();console.log(element.textContent); // Now 'Updated Content'}
svelte
Breakdown
1
import { tick } from 'svelte';
Import the lifecycle utility to wait for DOM updates.
2
await tick();
Pauses execution until the next microtask where the DOM has been synchronized with the state.
3
console.log(element.textContent);
After tick, the DOM content is guaranteed to match the updated 'message' variable.