Please help! I've been trying to solve this on my own, but keep hitting the wall.
Recreate the built in array method, forEach - Write a function that takes as parameters an array, arr, and a callback function, cb. The forEach function will iterate through arr passing each element and its index as arguments to cb. Create a variable named delays and assign to it an array with the numbers 200, 500, 0, and 350 (in that order). Write a function, delayLog, that takes as input a delayTime and an index, i. When invoked, the function should wait delayTime milliseconds before logging to the console, "printing element i" (with "i" replaced with the actual index passed in). Putting it all together, run the delayLog function on each item of the delays array using the forEach function you created.
This is what I have so far. Not too sure where to apply setTimeout. Thanks!!!
function forEach(array,cb){
for(let i=0;i<array.length;i++){
console.log("printing element",i)
}
}
let delays=[200,500,0,350];
function delayLog(delayTime,cb){
setTimeout(forEach(delayTime),cb);
}
delayLog(delays,i=>i)
FROM CONSOLE:
printing element 0
app.js:330 printing element 1
app.js:330 printing element 2
app.js:330 printing element 3
Here's what you want:
function forEach(arr, cb){
for(let i=0,l=arr.length; i<l; i++){
setTimeout(()=>{
cb(i);
}, arr[i]);
}
}
function delayLog(i){
console.log('printing element '+i);
}
forEach([200, 500, 0, 350], delayLog);