I have an array which have 200 elements like -100 to 100. I want to traverse or iterate this whole array in a specific time duration. for example I want to traverse or iterate this array in 5 second or also in 1 minutes. it's depend on user that , in how much time is define for traverse this whole array. How can i do it?
const array = [-100,-99,-98....0....98,99,100];
function traverseArr(){
....
}
You could take a function for the interval and calculate the duration for each element.
function traverseArray(array, time, fn) {
let i = 0;
const handle = setInterval(() => {
if (i < array.length) fn(array[i++]);
else clearInterval(handle);
}, time / array.length);
}
traverseArray([5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5], 10000, v => console.log(new Date().toISOString(), v));
.as-console-wrapper { max-height: 100% !important; top: 0; }