The setInterval
may not be a good one 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 that, 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 on Jsfiddle
I hope I helped the/
I find it unnecessary to have a global variable just to save the
.charAt
In that case it would be nice to have a variable fordocument.getElementById("texto")
, thus avoiding to always go to the GIFT to get it. Together alsovar
topartText
not to export to the global space.– Sergio