Aquí está la configuración. Estoy buscando detener la ejecución del looper (setInterval()) después de 5 segundos.
Tengo muchos comentarios, por lo que debería ser bastante fácil de entender, solo hágame cualquier pregunta para aclararlo.
He intentado mover la instrucción if (que verifica el valor del temporizador === 5000) alrededor. Lo probé dentro de la función setInterval, lo probé en la función onClick.
También intenté ejecutar setInterval() y clearInterval() con el prefijo window.
¿Alguna idea amigos? 🙏🏼 🥺
window.onload = function(){ var looper; var degrees = 0; var timer = 0; // timer used to monitor how long the wheel has been spinning function startWheelAnimation(elementId, speed){ // 1. get the element to rotate const ele = document.getElementById(elementId); // get the HTML element to rotate const cssRotateVal = "rotate("+degrees+"deg)"; // the CSS style rotate value // 2. CSS3 browser compatibility checks if(navigator.userAgent.match("Chrome")){ ele.style.WebkitTransform = cssRotateVal; } else if(navigator.userAgent.match("Firefox")){ ele.style.MozTransform = cssRotateVal; } else if(navigator.userAgent.match("MSIE")){ ele.style.msTransform = cssRotateVal; } else if(navigator.userAgent.match("Opera")){ ele.style.OTransform = cssRotateVal; } else { ele.style.transform = cssRotateVal; } // 3. start looping at the rate of speed var looper = setInterval( ()=>{ // at the rate of speed var run the following code startWheelAnimation( elementId, speed ); }, speed); degrees++; // increment the degrees value by 1 timer++; // increment the timer value by 1 console.log(timer); // devtool if( degrees > 359 ){ // reset the degrees value back to 0 upon a full rotation degrees = 0; clearInterval(looper); // stop the wheel spinning } if( timer === 5000 ){ // after 5 seconds has passed reset the timer and stop the looper console.log(looper); timer = 0; clearInterval(looper); // stop the wheel spinning } } document.getElementById('spinButton').addEventListener("click", event => { const speed = 100; startWheelAnimation("wheel", speed); }); }No debe crear un nuevo setTimerInterval en cada ejecución de la función. Esto acumulará diferentes intervalos activos, y solo tendrás la referencia al último que creaste.
En su lugar, mueva ese fragmento de código fuera de la función y colóquelo en el controlador de eventos que tiene como devolución de llamada de addEventListener :
document.getElementById('spinButton').addEventListener("click", event => { const speed = 100; const elementid = "wheel"; // schedule the repeated run: looper = setInterval( ()=>{ // at the rate of speed var run the following code startWheelAnimation(elementid, speed ); }, speed); // also run it immediately startWheelAnimation(elementid, speed); });Después de cada iteración - llamada startWheelAnimation , crea una nueva instancia de setInterval recursivamente (!) y la asigna a looper . Por lo tanto clearInterval solo borra la instancia más reciente.
Una solución sería verificar si los degrees o el timer están configurados en su valor inicial:
if (degrees == 0 || timer == 0) { looper = setInterval( ()=>{ // at the rate of speed var run the following code startWheelAnimation( elementId, speed ); }, speed); }