Kevin Doan Kevin Doan - 7 months ago 16
Javascript Question

Stop Looping Text but still run the effect

Example

var text = 'ENTER...';
var chars = text.split('');
var enter = document.getElementById("enter")
var i = 0;
setInterval (function(){
if (i < chars.length){
enter.innerHTML += chars[i++];
}else{
i = 0;
enter.innerHTML = "";
}
}, 200);


I'm trying to have this typing "enter" effect and I am wondering how to make it only go once. So it will type out "ENTER..." and then stop.
Example

Answer
var text  = 'ENTER...';
var enter = document.getElementById("enter")
var i = 0;
(function nextLetter() {
    enter.innerHTML = text.substr(0, ++i);
    if (i < text.length) {
        setTimeout(nextLetter, 200);
    }
})();

edit: you either have to use setTimeout (one time "sleep"), or remember return value of setInterval and destroy that timer by clearInterval after you don't need it/want it running.

Comments