【问题标题】:for loop that calls same function after previous iteration was completed在上一次迭代完成后调用相同函数的 for 循环
【发布时间】:2015-03-23 01:00:38
【问题描述】:

我正在尝试编写一个 for 循环,该循环遍历颜色数组并调用另一个函数,该函数使用该数组来更改按钮颜色。

目前我有一个三种颜色的数组,我希望按钮更改为第一种颜色然后等待然后变回白色然后更改为第二种颜色然后等待然后变为白色然后更改为第三种颜色并等待变成白色。

现在我有两个函数可以更改按钮的颜色,然后使用 setTimeout 等待 3 秒,然后再调用另一个函数将按钮更改回白色。

我的想法是在循环颜色的 for 循环中运行这个序列。 for 循环似乎正在触发,但在继续之前没有等待 setTimeouts 从上一次迭代完成。我想我可能需要回电,但不知道如何继续。

html:

<body>
  <button id="bigButton">Change Color</button>

  <script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
</body>

CSS:

button{
  background-color: white;
}

Javascript:

$("#bigButton").on('click', function(){
    var a=["blue", "green", "red"];
    for(var m=0; m<a.length; m++){
        turnOn(a[m]);
    }
});

var timerID = null;
function turnOn (inputColor) {
    $("#bigButton").css("background-color", inputColor)
    clearTimeout (timerID);
    timerID = null;
    if (timerID === null) {
        timerID = setTimeout ("turnOff()", 3000);
    }
}
function turnOff () {
    $("#bigButton").css("background-color", "white")
    clearTimeout (timerID);
    timerID = null;
}

codepen 是 here

【问题讨论】:

  • setTimeout 是异步的。您的循环立即将其变为蓝色,然后变为绿色,然后变为红色。然后 3 秒后它变回白色 3 次。
  • 您是否希望在单击 1 次后循环显示所有颜色?还是每次颜色变回白色后都要再点击一次?
  • 是的,我希望它在 1 次点击中循环播放

标签: javascript callback settimeout


【解决方案1】:

好的,我更新了jsFiddle 并提供了一个可行的解决方案。请让我知道这是否有效。

关键是将颜色数组移出,并根据递增的索引更改要查看的颜色:

var colors = ["blue", "green", "red"];
var currentIndex = 0;
var white = true;
$("#bigButton").on('click', function() {
  turnOn();
});

var timerID = null;

function turnOn() {
  if (!white) {
    white = true;
    inputColor = "white";
  } else {
    white = false;
    if (currentIndex === colors.length) {
      currentIndex = 0;
    }
    inputColor = colors[currentIndex];
    currentIndex++;
  }
  $("#bigButton").css("background-color", inputColor)
  console.log("color changed to ", inputColor);
  clearTimeout(timerID);
  timerID = null;
  if (timerID === null) {
    timerID = setTimeout("turnOff()", 3000);
  }
}

function turnOff() {
  $("#bigButton").css("background-color", "white")
  console.log("color changed to white");
  clearTimeout(timerID);
  timerID = null;
}

这是解决此问题的一种方法。您必须每次单击按钮才能更改颜色。

【讨论】:

  • 我该如何修改它,以便它自动循环遍历数组并更改颜色?无需每次点击?
  • 这里是更新后的jsFiddle。使用 setInterval。
猜你喜欢
  • 2018-10-23
  • 1970-01-01
  • 2017-07-27
  • 2016-11-04
  • 2023-01-13
  • 1970-01-01
  • 2019-06-05
  • 1970-01-01
  • 2018-01-20
相关资源
最近更新 更多