简体   繁体   中英

Javascript - How to wait event listener end to next iteration

I am facing problems with an event listener inside a for loop.

I have basically this:

 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(); } }

So, I have to wait window load in order to execute the function, and then go to next for iteration and do the same. But what I obtain looking this logs is:

    what??
    what??
    here
    here

How can I wait event listener finish between iterations ?

I'll just answer the question you actually asked...

How can I wait event listener finish between iterations ?

You can't do it with a real loop, the only way to make an asynchronous "loop" is to use recursion, which can be slightly complicated. The idea is to create a function that will call itself when it's ready to iterate again.

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

If you're looping over an array, the concept is similar... Here's a general purpose function I wrote to do do it...

 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); }); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM