Skip to content

Instantly share code, notes, and snippets.

@gtempesta
Created April 11, 2019 15:38
Show Gist options
  • Save gtempesta/42180cef6119216abc14fd8f3e859a38 to your computer and use it in GitHub Desktop.
Save gtempesta/42180cef6119216abc14fd8f3e859a38 to your computer and use it in GitHub Desktop.
Timed loop: jump to next iteration only if external conditions are met
// run a loop
// that jumps on the next iteration only after an external condition is met
// -> a poller checks on the condition every 100 ms and the iteration goes on only if certain conditions are met
// inspiration ->
// https://medium.com/@eric.stermer/setinterval-simply-put-is-a-timed-loop-652eb54bd5f8
// the `products` variable is defined elsewhere
// index
var i = 0;
// check if an asynchronous event has modified the specific item
var checkOnExternalConditions = function (i) {
return products[i].init === true;
};
// call the function on the specific item
var mainFunction = function (i){
// do something with i
products[i].addToCart();
}
var intervalId = setInterval(function () {
// check
if (checkOnExternalConditions(i)) {
// call the function
mainFunction(i);
// go to next iteration
i += 1;
}
if (i === products.length) {
// the loop ends when all the products have been checked
// any other operation that should run at the end of the loop should be placed here
clearInterval(intervalId);
}
}, 100);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment