Tengo un botón que realiza el registro de la consola en una matriz cada 500 ms en setInterval , quiero que cuando haga clic en el botón por primera vez, invoque la función en setInterval , luego vuelva a hacer clic en el botón, la consola detendrá el setInterval . Probé con este HTML, pero cuando hago clic en el botón por segunda vez, la consola sigue registrando la matriz. ¿Qué debo hacer para que la función esté inactiva o al menos setInterval esté inactivo?
var a = [2,3,4] var state = false; function addFunc() { if (state === false) { state = !state console.log(state); setInterval(() => { pushRandom(); }, 1000) } else if (state===true) { state = !state console.log(state); } } function pushRandom() { a.push(Math.random()) console.log(a) } <h1>The onclick Event</h1> <p>The onclick event is used to trigger a function when an element is clicked on.</p> <button onclick="addFunc()">add</button> <p id="demo"></p>Set Interval devuelve un Id que puede usar en clearInterval(Id) para detener el intervalo.
var intervalPushRandom; function addFunc() { if (state === false){ state = !state console.log(state); intervalPushRandom = setInterval(() => { pushRandom(); }, 1000) } else if (state===true){ clearInterval(intervalPushRandom); state = !state console.log(state); } }demostración completa:
<!DOCTYPE html> <html> <body> <h1>The onclick Event</h1> <p>The onclick event is used to trigger a function when an element is clicked on.</p> <button onclick="addFunc()">add</button> <p id="demo"></p> <script> var a = [2, 3, 4] var state = false; let myInterval; function addFunc() { if (state === false) { state = true; console.log(state); myInterval = setInterval(pushRandom, 1000); } else if (state === true) { state = false; console.log(state); clearInterval(myInterval); } } function pushRandom() { a.push(Math.random()); console.log(a); } </script> </body> </html>