【发布时间】:2021-11-09 22:42:18
【问题描述】:
我正在尝试使用 javascript 函数在我的网站上制作自定义打字机效果。为了在每个字母的输入之间添加延迟,我为 for 循环的每次运行实现了一个交错的setTimeout,因此与前一次相比,每次迭代都延迟了 300 毫秒。我需要将特殊字符(' ' 'else if 条件。当排除setTimeout 时,这会产生所需的效果。但是,添加延迟会导致在打印出整个字符后拼出此代码的各个字母。我该如何解决这个问题?
function type(fullTxt, current = '') {
for (let i = current.length, j = 0; i < fullTxt.length; i++, j++) {
setTimeout(function() {
if (fullTxt.substring(i, i+6) === ' ') {
console.log(fullTxt.substring(0, i+6));
i = i + 5;
} else if (fullTxt.substring(i, i+4) === '<') {
console.log(fullTxt.substring(0, i+4));
i = i + 3;
} else if (fullTxt.substring(i, i+3) === '>') {
console.log(fullTxt.substring(0, i+3));
i = i + 2;
} else {
console.log(fullTxt.substring(0, i+1));
}
console.log(j); //included just to ensure j is counting properly
console.log(i); //included to check progress of loop
console.log(fullTxt.length); //included to check endpoint of for loop
}, j * 300);
}
}
type('hello ');
预期输出:
// h
// 0
// 0
// 11
// he
// 1
// 1
// 11
// hel
// 2
// 2
// 11
// hell
// 3
// 3
// 11
// hello
// 4
// 4
// 11
// hello
// 5
// 10
// 11
【问题讨论】:
标签: javascript for-loop settimeout