I am trying to mimic the typing effect on the codility's home page in JavaScript.I have already achieved the typing and deleting effect using setInterval().
Here's the jsfiddle of that: https://jsfiddle.net/yzfb8zow/
var span=document.getElementById("content");
var strings=["hello world","how r u??"];
var index=0; //get string in the strings array
var chIndex=0; //get char in string
var type=true;
setInterval(function(){
if(index===strings.length)
index=0;
if(type){
typeIt();
}
else
deleteIt();
},200);
// type the string
function typeIt(){
if(chIndex<strings[index].length)
span.innerHTML=strings[index].substring(0,chIndex++);
else
type=false;
}
//delete the string
function deleteIt(){
if(chIndex===0){
index++;
type=true;
}
else
span.innerHTML=strings[index].substring(0,chIndex--);
}
the html
<span id="content"></span>
<span id="cursor">|</span>
the css
#cursor{
-webkit-animation: 1s blink step-end infinite;
-moz-animation: 1s blink step-end infinite;
animation: 1s blink step-end infinite;
}
@keyframes blink {
from, to {
opacity:0;
}
50% {
opacity: 1;
}
}
@-moz-keyframes blink {
from, to {
opacity:0;
}
50% {
opacity:1;
}
}
@-webkit-keyframes blink {
from, to {
opacity:0;
}
50% {
opacity:1;
}
}
What I can't get my head around is how could I pause the setInterval function at the beginning of string change and at the end to get a clear blinking cursor.
I have looked up other answers Pause and resume setInterval and How do I stop a window.setInterval in javascript? but I am unable to comprehend how to use it in this context.
Also it would be great if you could tell me how to improve my code.