打字机脚本错误

时间:2018-07-10 18:46:52

标签: javascript html arrays settimeout

我有问题。该脚本有什么问题,为什么在重置消息时一个字母出现并消失?如何解决? codepen.io

var i = 0;
var msgnow = 0;
var msg = ["Wiadomość 1", "Wiadomość 2", "Wiadomość 3"]; //message 1, 2, 3
var speed = 100;

function writeMessage() {
  setTimeout(writeMessage, speed);

  if (i < msg[msgnow].length) {
    document.getElementById("messagebar").innerHTML += msg[msgnow].charAt(i);
    i++;
  } else {
    setTimeout(resetMessages, 3000);
  }
}

function resetMessages() {
  document.getElementById("messagebar").innerHTML = "";
  msgnow++;
  i = 0;
  if (msgnow == msg.length) {
    msgnow = 0;
  }
}

writeMessage();
<span id="messagebar"></span>

1 个答案:

答案 0 :(得分:0)

您的writeMessage函数将立即(并始终)创建新的超时,而无需考虑前一个超时的间隔时间或是否有重置挂起。

尝试一次仅进行一次超时。此外,您应该将类​​型封装在其自己的范围内,以免没有这些全局变量。

请考虑以下更改:

var i = 0;
var msgnow = 0;
var msg = ["Wiadomość 1", "Wiadomość 2", "Wiadomość 3"]; //message 1, 2, 3
var speed = 100;
var messagebar = document.getElementById("messagebar");

function writeMessage() {
  if (i < msg[msgnow].length) {
    messagebar.innerHTML += msg[msgnow].charAt(i);
    i++;
    setTimeout(writeMessage, speed);
  } else {
    setTimeout(function() {
      resetMessages();
      setTimeout(writeMessage, speed);
    }, 3000);
  }

}

function resetMessages() {
  messagebar.innerHTML = "";
  msgnow++;
  i = 0;
  if (msgnow == msg.length) {
    msgnow = 0;
  }
}

writeMessage();
<span id="messagebar"></span>


这是我使用async / await的解决方案:

function $timeout(delay) {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(), delay);
  });
}

async function wr(el, word) {
  if (typeof word !== "string") throw new Error("Must provide a String");

  el.innerHTML = "";

  for (let i = 0; i < word.length; i++) {
    el.innerHTML += word[i];
    await $timeout(100);
  }

}

(async function() {
  const typewriterEl = document.getElementById("typewriter");
  await wr(typewriterEl, "hello world");
  await $timeout(1000);
  await wr(typewriterEl, "fizz buzz");
}());
<div id="typewriter"></div>