【发布时间】:2021-10-24 06:47:50
【问题描述】:
我试图让文本一次显示一个字母。我有一个不在函数内部的工作版本。我想将它全部放入一个函数中,但是我无法让它工作。当放入一个函数时,我遇到了一个问题,它说“.split”不是一个函数。
函数外的工作版本
let text = 'Lorem ipsum dolor sit, amet consectetur adipisicing elit.'
const textArray = text.split('');
let loopTimer;
const frameLooper = () => {
textArray.length > 0 ? document.querySelector('#text').innerHTML += textArray.shift() : clearTimeout(loopTimer);
loopTimer = setTimeout('frameLooper()', 30);
}
frameLooper()
函数内部(不工作)
let dialog = (text) => {
let textArray = text.split('');
return textArray;
}
let loopTimer
const frameLooper = (text) => {
let array = dialog(text)
array.length > 0 ? document.querySelector('#text').innerHTML += array.shift() : clearTimeout(loopTimer);
loopTimer = setTimeout('frameLooper()', 30);
}
frameLooper(dialog('This is a test'))
如果需要,这里是 HTML:
<p id="text" class="text-red-200"></p>
</div>
【问题讨论】:
-
setTimeout('frameLooper()'你没有传递参数,但是函数需要一个参数 -
避免将字符串传递给
setTimeout
标签: javascript html closures