Skip to content

Instantly share code, notes, and snippets.

@fernandojunior
Created October 29, 2014 23:06
Show Gist options
  • Save fernandojunior/1596ff6bce842a294920 to your computer and use it in GitHub Desktop.
Save fernandojunior/1596ff6bce842a294920 to your computer and use it in GitHub Desktop.
Simple JavaScript foreach lib with delay / timeout
// author: Fernando Felix do Nascimento Junior
// License: The MIT License
// example
forEach({
data: [1, 2, 3, 4, 5, 6],
timeout: 5000,
step_by: 2,
callback: function (value) {
console.log(value);
}
});
function forEach(config){
var ini = config.ini; // initial index
var data = config.data; // the data to lookup
var timeout = config.timeout; // timeout to call next index
var step_by = config.step_by; // step to call timeout
var callback = config.callback;
if (typeof ini == 'undefined')
ini = 0;
var step = ini + step_by;
if (step > data.length)
step = data.length;
for (var i = ini; i < step; i++){
callback(data[i]);
}
config.ini = step;
if (step < data.length) {
setTimeout(function(){
forEach(config);
}, timeout);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment