javascript - 无论如何有一个for循环等到一个间隔被清除

标签 javascript html node.js for-loop intervals

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

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

这是我的代码。

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)


  } 
}); 

} 
};

最佳答案

您想使用一个基本的队列,您可以使用 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();
    }

关于javascript - 无论如何有一个for循环等到一个间隔被清除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55612693/

相关文章:

php - jQuery/Js 循环 Codeigniter MySQL 输出数据

javascript - 相邻 HTML div 中的两个 float 图表导致问题

javascript - 禁用 html 文件中的脚本标签或使用 javascript 更改脚本标签类型/src

node.js - 如何生成 key 对并使用它来签名和验证 Node.js 中的文本?

javascript - 如何在 JavaScript 中使用格式示例 : 2018-01-22T11:48:39. 396000Z 获取当前时间?

javascript - 无法在 JQuery 中找到表单输入

javascript - Mongoose深度查找查询

HTML 三个并排的 div 具有相同的高度

node.js - Nodejs 包包含 CoffeeScript。该怎么办?

javascript - 如何存储旧消息