I had to achieve a typewriting effect that runs after every 3 seconds. I have used SetInterval for this. But couldn't get the result.
<!DOCTYPE html>
<html>
<body>
<h1>Typewriter</h1>
<button>Click me</button>
<p id="demo"></p>
<script>
var i = 0;
var txt = 'Lorem ipsum dummy text blabla.';
var speed = 50;
function mainTyping(){
if (i < txt.length) {
document.getElementById("demo").innerHTML += txt.charAt(i);
i++;
setTimeout(mainTyping, speed);
}
}
setInterval(mainTyping, 3000)
</script>
</body>
</html>
So I am writing this to make you understand how setInterval and setTimeout operate. Basically, when you call setInterval and pass in it a function what it does is after the specified time it triggers that function and whatever is in that function runs "completely" and after it has run "fully" it repeats the whole process again. Which means that if you are passing a function typeWriter in setInterval after 1s it will trigger the function, and now because in the call back function you have another setInterval which runs another function mainTyping what is happening is as soon as the typeWriter is fired, the setInerval within the call back runs after the specified time has passed the mainTyping function and after the main typing function has run fully, the handler then goes to the typeWriter function and this process repeats again and again within the specified time interval. I hope you understand what I just wrote. What this narrows down is to is that setInerval runs the function it is passed to completely and after it has run completely, it waits for the time you specified and runs the function again. You should learn about setInterval and setTimeout from here. Obvioulsy, yu can achieve the result by using setInterval and by using setTimeout however, setTimeout is better, you can read why in the article that I mentioned.
PS: Also, note when you click the click me button, "L" is typed pretty quickly than the rest of the letters because when the function typeWriter first runs is there is a setTimeout of "speed" seconds on the mainTyping function which is 50ms and nested in it is the function typeWriter which we are calling after every 1s and so the rest of the words are typed out after exactly 1s has passed.
var i = 0;
var txt = 'Lorem ipsum dummy text blabla.';
var speed = 50;
let button = document.querySelector("button");
function mainTyping(){
if (i < txt.length) {
document.getElementById("demo").innerHTML += txt.charAt(i);
i++;
}
}
function typeWriter() {
setTimeout((mainTyping),
setTimeout(typeWriter, 1000), speed);
}
button.addEventListener("click", typeWriter);
<!DOCTYPE html>
<html>
<body>
<h1>Typewriter</h1>
<button>Click me</button>
<p id="demo"></p>
</body>
</html>