Reputation: 404
I a script, in JavaScript, that makes a typewriting effect. I've tried to loop it, so that it executes in a loop after 10 seconds from the end of execution. In other words there is a typewriting effect and when the text is written after ten second code will execute once again. I've tried with setTimeout()
, however it did not work.
Thanks for help in advance.
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();
Upvotes: 0
Views: 1621
Reputation: 161
typewriter = setupTypewriter(typewriter);
You pass typewriter
variable to setupTypewriter
, but it doesn't exist yet. Here you want to use
typewriter = setupTypewriter(typer);
BTW, I can't understand how you print tags. You print <
, d
, i
, v
, >
with zero delay, but the parser still may break. You should print the tag at once: <div></div>
and then append div's contents to it.
Upvotes: 1
Reputation: 4888
You want setInterval.
setInterval(function(){ alert("Hello"); }, 3000);
This code will run every three seconds.
Full documentation, examples etc. here (including how to stop it):
https://www.w3schools.com/jsref/met_win_setinterval.asp
Upvotes: 1