Show text letter by letter

前端 未结 16 1520
旧巷少年郎
旧巷少年郎 2020-11-27 16:38

What is the most elegant way of showing an html text letter by letter (like videogame captions) using CSS and JavaScript?

While I\'m sure that his can be solved usin

16条回答
  •  Happy的楠姐
    2020-11-27 17:03

    Make your code more elegant by preparing promises for each iteration, then execute them as second step where you can inject DOM logic.

    const message = 'Solution using Promises';
    
    const typingPromises = (message, timeout) =>
      [...message].map(
        (ch, i) =>
          new Promise(resolve => {
            setTimeout(() => {
              resolve(message.substring(0, i + 1));
            }, timeout * i);
          })
      );
    
    typingPromises(message, 140).forEach(promise => {
      promise.then(portion => {
        document.querySelector('p').innerHTML = portion;
      });
    });

提交回复
热议问题