0 day streak
javascript / intermediate
Snippet

Waiting for DOM Updates with tick

In Svelte, state changes don't update the DOM immediately. They are batched for efficiency. The tick function returns a promise that resolves as soon as any pending state changes have been applied to the DOM.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
import { tick } from 'svelte';
let visible = false;
async function showAndFocus() {
visible = true;
await tick();
document.getElementById('input').focus();
}
svelte
Breakdown
1
await tick();
Pauses the function execution until the DOM has been synchronized with the latest state.
2
document.getElementById('input').focus();
Safely interacts with an element that might not have existed before the tick() resolved.