No entiendo qué hace que esta animación comience una y otra vez y cómo puedo detener esto después de jugar una vez. ¿Puede alguien ayudarme por favor? Para saber qué parte del código es responsable del bucle, eliminé diferentes partes del código una por una para ver cómo se ve afectado el resultado, pero aún no pude encontrarlo.
este es el HTML:
<a href="" class="typewrite" data-period="2000" data-type='[ "Hello.", "My name is B.", "I am just starting with HTML, CSS and JavaScript.", "Please bear with me..."]'> <span class="wrap"></span> </a>y aquí está el JavaScript:
var TxtType = function(el, toRotate, period) { this.toRotate = toRotate; this.el = el; this.loopNum = 0; this.period = parseInt(period, 10) || 2000; this.txt = ''; this.tick(); this.isDeleting = false; }; TxtType.prototype.tick = function() { var i = this.loopNum % this.toRotate.length; var fullTxt = this.toRotate[i]; if (this.isDeleting) { this.txt = fullTxt.substring(0, this.txt.length - 1); } else { this.txt = fullTxt.substring(0, this.txt.length + 1); } this.el.innerHTML = '<span class="wrap">'+this.txt+'</span>'; var that = this; var delta = 200 - Math.random() * 100; if (this.isDeleting) { delta /= 2; } if (!this.isDeleting && this.txt === fullTxt) { delta = this.period; this.isDeleting = true; } else if (this.isDeleting && this.txt === '') { this.isDeleting = false; this.loopNum++; delta = 500; } setTimeout(function() { that.tick(); }, delta); }; window.onload = function() { var elements = document.getElementsByClassName('typewrite'); for (var i=0; i<elements.length; i++) { var toRotate = elements[i].getAttribute('data-type'); var period = elements[i].getAttribute('data-period'); if (toRotate) { new TxtType(elements[i], JSON.parse(toRotate), period); } } // INJECT CSS var css = document.createElement("style"); css.type = "text/css"; css.innerHTML = ".typewrite > .wrap { border-right: 0.08em solid #f6fd96}"; document.body.appendChild(css); };El bucle de animación ocurre al final de la función TxtType.prototype.tick , cuando la función se vuelve a llamar a sí misma, recursivamente:
setTimeout(function() { that.tick(); }, delta) setTimeout es una función que ejecuta algo después de un tiempo. En ese caso, está ejecutando that.tick() después del tiempo delta .
Si desea que se repita solo una vez, puede usar la información this.loopNum para crear una condición alrededor de las líneas anteriores:
if(this.loopNum < 1) { setTimeout(function() { that.tick(); }, delta) }usó recursividad para llamar a la función tick () cada ms delta. Aquí es donde está el bucle.
TxtType.prototype.tick = function() { // ... setTimeout(function() { that.tick(); }, delta); }
Si desea solo este código una vez. Agregue la condición de parada para la recursividad.
if (this.loopNum < this.toRotate.length) { setTimeout(function() { that.tick(); }, delta); }