<script>
import {onMount} from 'svelte'
let phrase = "Head Admin Esports Middle East organization ( es.me website) and Project Manager at Arab Esports Website."
let typedChar = "";
let index = 0;
let aud;
const typing = () => {
setInterval(async () => {
if (index < phrase.length) {
typedChar += phrase[index];
index++;
await aud.play()
} else {
clearInterval()
}
}, 20)
}
onMount(() => {
typing()
})
</script>
<audio bind:this={aud} src={typingAudio} />
Here I am showing the data in typing effect I wanted to add sound to this typing effect it works fine as I wanted but when I leave the component mid typing it shows Cannot read properties of null ( play ) error
This might be because the interval isn't cleared - there's neither an id provided in the call inside typing
nor is it cleared when the component is destroyed
clearInterval()
- If the parameter provided does not identify a previously established action, this method does nothing.
let interval
const typing = () => {
interval = setInterval(async () => {
if (index < phrase.length) {
typedChar += phrase[index];
index++;
await aud.play()
} else {
clearInterval(interval)
}
}, 20)
}
onMount(() => {
typing()
return () => clearInterval(interval)
})
Alternatively to onDestroy
If a function is returned from onMount, it will be called when the component is unmounted.
(playing the audio might be blocked if the user hasn't yet interacted with the page)