无论如何都有一个for循环等待,直到间隔已经清除

问题描述 投票:1回答:1

我有一个针对节点列表运行的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个回答
2
投票

你想使用一个基本的队列,你用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集合转换为数组来获得转换

const seats = Array.from(document.querySelectorAll(seatSectionSelector));
function nextItem() {
  var seat = seats.shift();
  seat.dispatchEvent(...);
  const popupInterval = setInterval(() => {
    ...
    if (popupBtn) {
      ...
      if (seats.length) nextItem();
    }
© www.soinside.com 2019 - 2024. All rights reserved.