0 day streak
javascript / beginner
Snippet

Creating Time-Delayed State Changes with JavaScript Promises

Wrapping setTimeout in a Promise allows you to use async and await syntax for time-based coordination. In UI applications, this makes sequential asynchronous state updates, such as showing temporary loading messages or notifications, straightforward and easy to follow.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<script>
let status = 'Idle';
function delay(milliseconds) {
return new Promise(resolve => setTimeout(resolve, milliseconds));
}
async function triggerAction() {
status = 'Processing...';
await delay(1500);
status = 'Completed successfully!';
}
</script>
<button on:click={triggerAction}>Start Process</button>
<p>Status: {status}</p>
svelte
Breakdown
1
function delay(milliseconds) {
Creates a helper function that returns a Promise resolving after the specified timeout.
2
async function triggerAction() {
Defines an asynchronous function that can pause execution using the await keyword.
3
await delay(1500);
Pauses execution for 1500 milliseconds before updating the status to completed.