0

I am just playing around with the setInterval function in JavaScript. I am wondering if there is a way to toggle the setInterval with an HTML button

This is my code.

let x = 0;
const listener = document.getElementById('listener');
const numberPlace = document.getElementById('numberPlace');

const numberCounter = setInterval(() => {
  x++;
  numberPlace.innerHTML = x;
}, 100);

listener.addEventListener('click', numberCounter);

The problem is that the number starts counting when the page loads and not on a button click.

Please help

  • Checkout: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval – thedude Feb 12 '20 at 14:33
  • 3
    Make `numberCounter` *a function* which when called calls `setInterval`. Currently it's the return value of calling `setInterval`… – deceze Feb 12 '20 at 14:34
  • Does this answer your question? [Stop setInterval call in JavaScript](https://stackoverflow.com/questions/109086/stop-setinterval-call-in-javascript) – thedude Feb 12 '20 at 14:34
  • @thedude It doesn't. – deceze Feb 12 '20 at 14:34
  • It looks like typo problem. Just need to wrap `numberCounter` with `function () {}` – Tân Feb 12 '20 at 14:35
  • 1
    Your actual question is "how do I run code when a button is clicked", and I imagine you should be able to find existing answers that show how to do this correctly. –  Feb 12 '20 at 14:41

2 Answers2

2
const numberCounter = () => setInterval(() => {
  x++;
  numberPlace.innerHTML = x;
}, 100);
Ghonima
  • 2,978
  • 2
  • 14
  • 23
0

setInterval can be cancelled using clearInterval and the integer identifier returned when setInterval was called.

To toggle a setInterval-based counter, you simply need to toggle on the presence (or absence) of this identifier.

let counter = 0;
let intervalId = null;
const btn = document.getElementById('btn');
const numberPlace = document.getElementById('numberPlace');

const numberCounter = () => intervalId === null
    ? intervalId = setInterval(() => numberPlace.innerHTML = ++counter, 100)
    : (clearInterval(intervalId), intervalId = null)

btn.addEventListener('click', numberCounter);
<button id="btn">toggle</button>
<div id="numberPlace"></div>
Ben Aston
  • 53,718
  • 65
  • 205
  • 331