javascript / beginner
Snippet
Scheduling Temporary Flash Messages with SetTimeout in Vue
JavaScript's built-in asynchronous setTimeout function schedules a callback function to execute after a specified delay in milliseconds. In Vue, this allows temporary reactive state changes, such as clearing a flash alert message automatically after 3 seconds.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
<script setup>import { ref } from 'vue';const notification = ref('');function triggerAlert(message) {notification.value = message;setTimeout(() => {notification.value = '';}, 3000);}</script>
vue
Breakdown
1
notification.value = message;
Sets the reactive message text immediately so the UI displays the alert.
2
setTimeout(() => {
Registers an asynchronous callback to run in the background after the delay.
3
notification.value = '';
}, 3000);
Resets the reactive notification back to an empty string after 3000 milliseconds.