简体   繁体   中英

Asynchronous JavaScript Challenge question with setTimeout and recreating forEach

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);

function forEach(arr, cb){
  for(let i = 0; i < arr.length; i++){
    cb(arr[i], i);
  }
}

 delays = [200, 500, 0, 350];

function delayLog(delayTime, i){
  setTimeout(() => {
    console.log(`printing element ${i}`)
  }, delayTime);
}

forEach(delays, delayLog);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM