原理是每次截取前几个字,截取前清空打印,可以通过调整time改变打字效果,废话不多说,直接上菜
const data = {
time:300,
txt: `
你好,我是XXX,
你叫什么名字?
你的爱好是什么?
`
}
async function main(){
let index = 0;
const { time,txt } = data;
while ( index < txt.length){
print(index,txt);
await delay(time);
index ++;
}
}
main()
function delay(time){
return new Promise((resolve) => setTimeout(()=>resolve(),time))
}
function print(index,txt){
console.clear();
const output = txt.substring(0,index)
console.log(output)
}
效果: