javascript - 更改 onclick 处的 Setinterval

标签 javascript html

我正在尝试使用 onclick 函数更改这两个框的速度(setinterval)。 到目前为止,我让两个框改变颜色,并将Interval设置为1000(ms),现在我想单击其中一个框,我希望它们改变颜色的速度。

 setInterval(
    function(){
        if (quadraDo == true) {
            document.getElementById("demo0").style.background = "red"
            document.getElementById("demo1").style.background = "blue";
            
            quadraDo = false;
        }
        else if (quadraDo == false) {
            document.getElementById("demo0").style.background = "blue";
            document.getElementById("demo1").style.background = "red";
            quadraDo = true;
        }
    
    
    }, 1000);
    
    <div id="demo0" style="position: absolute;background-color: chartreuse ; width: 100px;height: 100px;left: 100px;top: 100px;"  onclick="myFunction(this)"></div>
    <div id="demo1" style="position: absolute;background-color: chartreuse ; width: 100px;height: 100px;left: 300px;top: 100px;"  onclick="myFunction(this)"></div>

最佳答案

一些解释。我使用您的代码创建了一个函数 changeColor ,该函数的初始间隔速度为 1000ms

然后,单击任何一个方 block 后,初始计时器将被清除,并以不同的间隔速度开始新的计时器。在这种情况下:

  • 点击第一个方 block 会减慢初始节奏 (x0.5) 或 500 毫秒
  • 点击第二个可加快初始节奏 (x2) 或 2000 毫秒

这样 myFunction 就可以被重用来设置初始速度并在单击时更改速度。最重要的部分是在开始新的间隔之前清除当前的间隔。

let quadraDo = false;
function changeColor() {
  if (quadraDo == true) {
    document.getElementById("demo0").style.background = "red";
    document.getElementById("demo1").style.background = "blue";
    quadraDo = false;
  } else if (quadraDo == false) {
    document.getElementById("demo0").style.background = "blue";
    document.getElementById("demo1").style.background = "red";
    quadraDo = true;
  }
}

function myFunction(speed) {
  clearInterval(timer);
  timer = setInterval(changeColor, speed);
}

let timer = setInterval(changeColor, 1000);
<div id="demo0" style="position: absolute;background-color: chartreuse ; width: 100px;height: 100px;left: 100px;top: 100px;"  onclick="myFunction(500)"></div>
<div id="demo1" style="position: absolute;background-color: chartreuse ; width: 100px;height: 100px;left: 300px;top: 100px;"  onclick="myFunction(2000)"></div>

顺便说一句,您在复制粘贴代码时出现拼写错误:

document.getElementById.setInterval("demo0",100).style.background = "red"

应该是:

document.getElementById("demo0").style.background = "red"

关于javascript - 更改 onclick 处的 Setinterval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58996689/

相关文章:

javascript - 在 javascript 程序中使用 rowspan

javascript - 如果输入或 div 被禁用,则添加一个类

javascript - 获取 iframe 的源代码

java - Tapestry 5.4 和 HTML5 音频标签

javascript - Angular 7 - promise 内的 forEach 迭代在 promise 解决后执行。为什么?

javascript - Webkit 滞后于 Canvas 中的大图像

html - rails : Image as a link

javascript - 在 Windows 8 平板电脑上处理虚拟键盘

javascript - 如何使用js/html对表格进行排序

javascript - jQuery 窗口宽度不等于 CSS 的窗口宽度