I am trying to make a game with HTML, CSS and JS which involves a typewriting animation. I want a custom function which when called, typewrites some text. However, there is a problem when using the function multiple times. The function combines the text from the different strings which are inputted. in the function. Please help me find a solution to this. My code is similar to the W3 Schools example code with a few changes.
var txt, speed, i;
function typeWriter() {
if (i < txt.length) {
document.getElementById("text").innerHTML += txt.charAt(i);
i++;
setTimeout(typeWriter, speed);
}
}
function write(whatToWrite, howFast) {
i = 0;
txt = whatToWrite;
speed = howFast;
typeWriter();
}
//There is a problem when called multiple times
write("hello", 100);
write("world", 100);
html{
background-color: #0a1c08;
color: #ffffff;
font-size: 20px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>The Game of Destiny</title>
<link href="https://fonts.googleapis.com/css?family=Inconsolata&display=swap" rel="stylesheet">
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<p id="text"></p>
</body>
</html>
<script src="typewriter.js"></script>