简体   繁体   English

有没有办法切换 setInterval

[英]Is there a way to toggle a setInterval

I am just playing around with the setInterval function in JavaScript.我只是在玩 JavaScript 中的 setInterval 函数。 I am wondering if there is a way to toggle the setInterval with an HTML button我想知道是否有办法用 HTML 按钮切换 setInterval

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请帮忙

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

setInterval can be cancelled using clearInterval and the integer identifier returned when setInterval was called. setInterval可以使用取消clearInterval并且当标识符返回的整数setInterval被调用。

To toggle a setInterval -based counter, you simply need to toggle on the presence (or absence) of this identifier.要切换基于setInterval的计数器,您只需切换此标识符是否存在(或不存在)。

 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM