【问题标题】:Is there anyway of having a for loop wait until an interval have cleared是否有一个 for 循环等待直到间隔清除
【发布时间】:2019-04-10 12:33:44
【问题描述】:

我有一个针对节点列表运行的 for 循环。我正在尝试遍历节点列表并触发点击,然后我设置一个间隔来等待弹出窗口,然后我想在弹出窗口中触发点击。

我的问题是我需要每次迭代都等到加载弹出窗口并且在进入下一个迭代之前单击弹出窗口中的项目。希望这是有道理的。

这是我的代码。

let checkSteats = () => {
  const seats = document.querySelectorAll(seatSectionSelector);
  if (seats.length < maxSeatCount) {
    maxSeatCount = seats.length;
  }

  if (seats.length > 0) {

    [].forEach.call(seats, (seat, index) => {
  /**
   * WE NEED TO CLICK WAIT FOR A CHANGE IN THE RESPONSE OR POP UP BEFORE WE GO INTO THE NEXT ITERATION
   */
  console.log(seat)
  if ((index+1) <= maxSeatCount) {

    seat.dispatchEvent(
      new MouseEvent('click', {
        view: window,
        bubbles: true,
        cancelable: true,
        buttons: 1
      })
    );

    const popupInterval = setInterval(() => {
      const popupBtn = document.querySelector('.ticket-option__btn');

      if (popupBtn) {
        popupBtn.click();
        clearInterval(popupInterval);
      }
    }, 100)


  } 
}); 

} 
};

【问题讨论】:

  • 您不应该为此使用循环。应该是从数组中转移()项目的方法。

标签: javascript html node.js for-loop intervals


【解决方案1】:

您想使用一个基本队列,在该队列中使用 shift() 从数组的前面拉出项目

var myArray = [1, 2, 3, 4]

function nextItem() {
  var item = myArray.shift();
  window.setTimeout(function() {
    console.log(item);
    if (myArray.length) nextItem();
  }, 1000)
}
nextItem()

因此,在您的情况下,您将在清除间隔时调用 nextItem() 。您可以通过将 html 集合转换为数组来获得 shift

const seats = Array.from(document.querySelectorAll(seatSectionSelector));
function nextItem() {
  var seat = seats.shift();
  seat.dispatchEvent(...);
  const popupInterval = setInterval(() => {
    ...
    if (popupBtn) {
      ...
      if (seats.length) nextItem();
    }

【讨论】:

  • 不是 100% 关于如何将其合并到我的代码中。
  • 得到它的工作伙伴 - 非常感谢你一个完整的生命拯救者!我欠你一个!!!
猜你喜欢
  • 2022-01-09
  • 2021-07-23
  • 2023-01-20
  • 2020-02-21
  • 1970-01-01
  • 2022-01-22
  • 1970-01-01
  • 1970-01-01
  • 2014-08-16
相关资源
最近更新 更多