按时间间隔循环 javascript 函数

Looping javascript function on time intervals

我在 JavaScript 中编写了一个脚本,它具有打字效果。我试图循环它,以便它在执行结束后 10 秒后循环执行。换句话说,有一个打字效果,当文本在十秒后被写入时,代码将再次执行。我试过 setTimeout(),但是没有用。

提前感谢您的帮助。

function setupTypewriter(t) {
  var HTML = t.innerHTML;

  t.innerHTML = "";

  var cursorPosition = 0,
      tag = "",
      writingTag = false,
      tagOpen = false,
      typeSpeed = 50,
      tempTypeSpeed = 0;

  var type = function() {

    if (writingTag === true) {
      tag += HTML[cursorPosition];
    }

    if (HTML[cursorPosition] === "<") {
      tempTypeSpeed = 0;
      if (tagOpen) {
        tagOpen = false;
        writingTag = true;
      } else {
        tag = "";
        tagOpen = true;
        writingTag = true;
        tag += HTML[cursorPosition];
      }
    }
    if (!writingTag && tagOpen) {
      tag.innerHTML += HTML[cursorPosition];
    }
    if (!writingTag && !tagOpen) {
      if (HTML[cursorPosition] === " ") {
        tempTypeSpeed = 0;
      }
      else {
        tempTypeSpeed = (Math.random() * typeSpeed) + 50;
      }
      t.innerHTML += HTML[cursorPosition];
    }
    if (writingTag === true && HTML[cursorPosition] === ">") {
      tempTypeSpeed = (Math.random() * typeSpeed) + 50;
      writingTag = false;
      if (tagOpen) {
        var newSpan = document.createElement("span");
        t.appendChild(newSpan);
        newSpan.innerHTML = tag;
        tag = newSpan.firstChild;
      }
    }

    cursorPosition += 1;
    if (cursorPosition < HTML.length - 1) {
      setTimeout(type, tempTypeSpeed);
    }

  };

  return {
    type: type
  };
}

var typer = document.getElementById('typewriter');

typewriter = setupTypewriter(typewriter);

typewriter.type();

你想要setInterval。

setInterval(函数(){ 警报("Hello"); }, 3000);

此代码每三秒 运行。

这里有完整的文档、示例等(包括如何停止它):

https://www.w3schools.com/jsref/met_win_setinterval.asp

typewriter = setupTypewriter(typewriter);

您将 typewriter 变量传递给 setupTypewriter,但它还不存在。这里要用

typewriter = setupTypewriter(typer);

顺便说一句,我不明白你是如何打印标签的。您以零延迟打印 <div>,但解析器仍可能中断。您应该立即打印标签:<div></div> 然后将 div 的内容附加到它。