我是一个JavaScript脚本,它具有打字效果。我试图循环它,以便它在执行结束10秒后循环执行。换句话说,就是有一种打字效果,并且当文字在十秒钟后写入时将再次执行一次。我试过setTimeout()
,但它没有奏效。按时间间隔循环的javascript函数
感谢您的帮助。
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();
感谢分享。我已经看到了,但是我不确定如何在我的函数中使用它。 JS对我来说是新的(我通常使用C#)。正如你可以在底部看到有三行代码,没有它们,打字效果不起作用。当我使用类似var myVar的代码时; function myFunction(){ myVar = setInterval(setupTypewriter,3000); }该函数执行onces(仅在显示效果后),就是这样。没有更多发生。 – Mikisz