If you are using ECMAScript6 , you can use Promise .
So, create a delay function that ends the setTimeout call in Promise:
function delay(ms) { return new Promise(function (resolve) { return setTimeout(resolve, ms); }); };
And you can use it like this:
someFunction(listings, function() { for (var i in listings ) { var listing = listings[i]; delay(5000).then(() => { return asyncFunction(listing); }).then(() => { console.log('Done'); }); } });
If you are using ECMAScript 2017 , you can use aync / WAIT .
Async functions return a promise, so you do not need to change the delay function code.
async someFunction(listings, function() { for (var i in listings ) { var listing = listings[i]; await delay(5000); await asyncFunction(listing); console.log('Done'); } });
source share