簡體   English   中英

Javascript - 如何等待事件偵聽器結束到下一次迭代

[英]Javascript - How to wait event listener end to next iteration

我在 for 循環中遇到事件偵聽器的問題。

我基本上是這樣的:

 for (var i = 0; i < 2; i++) { //window url change here, each iteration open a different url console.log('what??'); window.addEventListener('load', aperture, true); function aperture() { console.log('here'); window.close(); } }

因此,我必須等待窗口加載才能執行該函數,然后轉到 next 進行迭代並執行相同的操作。 但是我通過查看此日志獲得的是:

    what??
    what??
    here
    here

如何在迭代之間等待事件偵聽器完成?

我就回答你實際問的問題...

如何在迭代之間等待事件偵聽器完成?

你不能用真正的循環來做到這一點,制作異步“循環”的唯一方法是使用遞歸,這可能有點復雜。 這個想法是創建一個函數,當它准備好再次迭代時會調用自己。

 (function myLoop(){ // do something that takes a while setTimeout(function(){ console.log("did something"); // then recurse... myLoop(); }, 1500); })();

如果你在一個數組上循環,這個概念是相似的......這是我寫的一個通用函數來做到這一點......

 var myArray = ["a","b","c","d"]; var myLoop = slowLoop(myArray, (itm, idx, cb)=>{ setTimeout(()=>{ console.log(`doing something with ${itm} which is item number ${idx} in the array`); // call cb when finished cb(); }, 1000); }); // when it's done.... myLoop.then(()=>{ console.log("All done looping"); }); /** * Execute the loopBody function once for each item in the items array, * waiting for the done function (which is passed into the loopBody function) * to be called before proceeding to the next item in the array. * @param {Array} items - The array of items to iterate through * @param {Function} loopBody - A function to execute on each item in the array. * This function is passed 3 arguments - * 1. The item in the current iteration, * 2. The index of the item in the array, * 3. A function to be called when the iteration may continue. * @returns {Promise} - A promise that is resolved when all the items in the * in the array have been iterated through. */ function slowLoop(items, loopBody) { return new Promise(f => { done = arguments[2] || f; idx = arguments[3] || 0; let cb = items[idx + 1] ? () => slowLoop(items, loopBody, done, idx + 1) : done; loopBody(items[idx], idx, cb); }); }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM