gpt4 book ai didi

javascript - 关闭JavaScript html中的功能

转载 作者:行者123 更新时间:2023-12-02 01:48:59 25 4
gpt4 key购买 nike

我有一个按钮,在setInterval中每500毫秒执行控制台记录一个数组,我希望当我第一次单击该按钮时,我调用setInterval中的函数,然后我再次单击该按钮,控制台将停止 setInterval。我尝试使用此 HTML,但当我第二次单击该按钮时,控制台仍然记录该数组。我应该怎么做才能使该函数处于非事件状态或至少 setInterval 处于非事件状态?

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 返回一个 Id,您可以在 clearInterval(Id) 中使用该 Id 来停止 Interval。


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);
}
}

完整演示:

<!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>

关于javascript - 关闭JavaScript html中的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70562653/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com