JS 将一个字符串进行逐字显示的方法汇总
毋庸置疑,现在chatGTP是非常火热的,在这个时候公司项目中提到了AI智能对话UI显示界面模仿chatGTP的UI一样,显示答案不能一蹴而就,而要逐字逐字显示。至此,我先学习一个JS版本的。
- 使用setTimeout()函数和for循环:
const sentence = "Hello World"; let index = 0; function displayLetter() { console.log(sentence[index]); index++; if (index < sentence.length) { setTimeout(displayLetter, 1000); } } displayLetter();
- 使用setInterval()函数和slice()方法:
const sentence = "Hello World"; let index = 0; const intervalId = setInterval(() => { console.log(sentence.slice(index, index + 1)); index++; if (index >= sentence.length) { clearInterval(intervalId); } }, 1000);
- 使用async/await和Promise对象:
const sentence = "Hello World"; async function displayLetter() { for (let letter of sentence) { await new Promise(resolve => { setTimeout(() => { console.log(letter); resolve(); }, 1000); }); } } displayLetter();
- 使用Generator函数:
const sentence = "Hello World"; function* displayLetter() { for (let letter of sentence) { yield new Promise(resolve => { setTimeout(() => { console.log(letter); resolve(); }, 1000); }); } } const generator = displayLetter(); function runGenerator() { const next = generator.next(); next.value.then(() => { if (!next.done) { runGenerator(); } }); } runGenerator();
- 使用reduce()方法和Promise对象:
const sentence = "Hello World"; sentence.split('').reduce((promise, letter) => { return promise.then(() => new Promise(resolve => { setTimeout(() => { console.log(letter); resolve(); }, 1000); })); }, Promise.resolve());
- 使用递归函数:
const sentence = "Hello World"; let index = 0; function displayLetter() { if (index < sentence.length) { console.log(sentence[index]); index++; setTimeout(displayLetter, 1000); } } displayLetter();
- 使用map()方法和Promise对象:
const sentence = "Hello World"; Promise.all(sentence.split('').map((letter, index) => { return new Promise(resolve => { setTimeout(() => { console.log(letter); resolve(); }, index * 1000); }); }));
- 使用forEach()方法和setTimeout()
const sentence = "Hello World"; sentence.split('').forEach((letter, index) => { setTimeout(() => { console.log(letter); }, index * 1000); });
原文地址:https://blog.csdn.net/qq_44327851/article/details/136201219
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!