I am currently facing an issue with a function that is designed to switch words every few seconds. The functionality itself is working fine, but I keep encountering the following error intermittently in the VSC console:
TypeError: Cannot set properties of null (setting 'textContent') at Timeout._onTimeout (.../components/home/Hero.vue:36:28) at listOnTimeout (node:internal/timers:564:17)
It's puzzling because when I console.log word.value
, I can see that the element is being accessed successfully. This indicates that the function is indeed changing the words as intended, yet the error persists. I find this discrepancy confusing and am unsure how to troubleshoot it effectively. It's worth noting that the error only surfaces in the VSC console, not in Google Chrome's console.
<span ref="word"></span>
onMounted(() => {
randomizeText()
wordChanger
})
onBeforeRouteLeave(() => {
clearTimeout(wordChanger)
})
const wordChanger = setInterval(randomizeText, 4000)
const word = ref(null)
const words = reactive(['Word-1', 'Word-2'])
let i = 0
function randomizeText() {
i = randomNum(i, words.length)
const newWord = words[i]
setTimeout(() => {
word.value.textContent = newWord
}, 200) // time to allow opacity to hit 0 before changing word
}
function randomNum(num, max) {
let j = Math.floor(Math.random() * max)
// ensure diff num every time
if (num === j) {
return randomNum(i, max)
} else {
return j
}
}