I was working on a typewriter effect for a web page with the use of java script.
const wordList = ["word 1","word 2","word 3"];
let word = wordList[0];
let temp = "";
let complete = false;
let i = 0;
let blinkTime = 650;
let type = ()=>{
async function myDisplay(){
let myPromise = new Promise(function (res,rej){
setTimeout(function(){
if(!complete){
temp = word.slice(0,temp.length + 1);
}
else{
temp = word.slice(0,temp.length - 1);
}
res(temp);
},Math.floor(Math.random()*300 + 100));
});
document.getElementById("type").innerHTML = await myPromise;
}
myDisplay().then(function (){
if(temp===word && !complete){
complete = true;
setTimeout(function(){type();},3000);
}
else if (temp === "" && complete){
complete = false;
i = (i+1)%wordList.length;
word = wordList[i]
type();
}
else{
type();
}
});
}
let blink = function(){
let myPromise = new Promise(function(res){
setTimeout(function() {
document.getElementById("type").style.borderRightStyle = "solid";
},blinkTime);
res();
});
myPromise.then(function(){
setTimeout(function() {
document.getElementById("type").style.borderRightStyle = "none";
blink();
},2*blinkTime);
});
}
type();
blink();
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]> <html class="no-js"> <!--<![endif]-->
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="">
</head>
<body>
<!--[if lt IE 7]>
<p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="#">upgrade your browser</a> to improve your experience.</p>
<![endif]-->
<span id="type"></div>
<span id="type2"> hello there</div>
<script src="./script/myScript.js" async defer></script>
</body>
</html>
The program runs perfectly fine, but I am a novice in java script and to my knowledge recursive calls that don't have a proper end is not a good programming practice. In the above java script code the type()
function and the blink()
function never end their recursive calls, is this a concerning issue that might break the webpage, or am I missing some concept here ?