setInterval
may not be good, because it repeats indefinitely (until it is determined that it stops with clearInterval
).
What I recommend is that you use setTimeout
that runs only once.
With this, your code would look something like this:
var partText = "";
function escreverNoObjeto (objeto, texto) {
objeto.innerHTML = texto;
}
function escrever(text, intervalo) {
var partText = '';
var fn = function(texto) {
return function() {
/* pode ser document.getElementById("texto")*/
escreverNoObjeto(document.body, texto);
};
};
for (i = 0; i < text.length; i++) {
partText += text.charAt(i);
setTimeout(fn(partText), intervalo * (i + 1));
}
}
escrever("teste", 1000);
You can still see it working in JSFiddle
I hope I have helped \ o /