What I am doing is an effect that makes it look like a text that is written by itself, the code I have is the following:
It's a simple <body>
with two elements to see the example (also in: jsfiddle ).
$("#write").click(function() {
//Es un fragmento de texto extraido del periódico "El país"
var text = "Llamada oculta. Al otro lado del teléfono suena una voz muy grave, fuerte, de un hombre con un inglés de ligero acento escandinavo. Soy Lars Hedegaard, creo que querías hablar conmigo. Verse no es posible. Ni se encuentra en Copenhague ni puede dar su paradero al estar bajo protección policial. Hedegaard, historiador y periodista danés de 74 años, es un reconocido y duro crítico del islam. Le grabaron en su casa, sin previo aviso según defiende, diciendo cosas como que en las familias musulmanas, las niñas eran violadas por padres, tíos y sobrinos. Por esto fue multado en 2011 con unos 700 euros.";
var writer = "";
writer.length = 0; //Limpiar el string
var maxLength = text.length;
var count = 0;
var speed = 5000 / maxLength; //La velocidad varía dependiendo de la cantidad de caracteres
var write = setInterval(function() {
if (count > text.length) {
clearInterval(write);
}
writer += text.charAt(count);
document.getElementById("text").innerHTML = writer;
count++;
}, speed);
$("#write").click(function() {
clearInterval(write);
}); //si se pulsa en el botón limpiar el intervalo
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="write" type="button">Write!</button>
<h1 id="text"></h1>
The doubt I have is that I don't know if I am using the correct method to do it. That is to say, I am not clear if it would be better to use the loop for
, or to use setInterval
(as it is in the example), also if the code can be simplified even more than it is.
But of course, if I use for
I'll have to put a setTimeout
into it... that's what I'm mulling over.
Based on your code. and using
setInterval(function(){
With
setInterval
is fine. I give you an example usingsetInterval
andGeneradores
from ES6. I use the generator to generate , forgive the redundancy, line by line from a given text.Note: code will only work in browsers that support
Generators
.EDITION
Since I have improved the code and functionality of this answer for my personal use, I am sharing it with the community:
ORIGINAL ANSWER
I wrote a similar answer on StackOverflow a while back , which uses Promises.
The following example uses Observables from the RxJS library.
As you mention in your question you can use
setTimeout()
to display each character in a specified time interval.This would display the "typeWriter" effect on your page.