I have encountered a simple issue while using an if statement within a function.
The following code is working as intended:
<!DOCTYPE html>
<html>
<body>
<h1>Typewriter</h1>
<button onclick="typeWriter()">Click me</button>
<p id="demo"></p>
<script>
var i = 0;
var txt = 'Lorem ipsum dummy text blabla.';
var speed = 50;
function typeWriter() {
if (i < txt.length) {
document.getElementById("demo").innerHTML += txt.charAt(i);
i++;
setTimeout(typeWriter, speed);
}
}
</script>
</body>
</html>
However, when I declare the variables inside the function, it seems to continuously repeat the first letter of the variable text. What could be causing this?
Here's the modified code:
<!DOCTYPE html>
<html>
<body>
<h1>Typewriter</h1>
<button onclick="typeWriter()">Click me</button>
<p id="demo"></p>
<script>
function typeWriter() {
var i = 0;
var txt = 'Lorem ipsum dummy text blabla.';
var speed = 50;
if (i < txt.length) {
document.getElementById("demo").innerHTML += txt.charAt(i);
i++;
setTimeout(typeWriter, speed);
}
}
</script>
</body>
</html>