Home > other >  Return an array containing the timeout objects for each timeout that's set
Return an array containing the timeout objects for each timeout that's set

Time:09-30

So I'm being asked to write a function in JS that will accept an array of callbacks and an array of delays that sets a timeout for each callback in the array with its corresponding delay. This is the code I have that checks off at least one of the solutions of corresponding callback and delay:

function batchTimeouts(callbacks, delays) {
  for(let i = 0; i < 3; i  ){
    setTimeout(callbacks[i], delays[i]);
  }
}

The problem is that it should return an array containing the timeout objects that return after each call to setTimeout. I'm not exactly sure what I'm doing, I've tried rewriting it in different parts but ultimately I get a TypeError: cannot read properties of undefined. I'm a bit of a slow learner so I appreciate any help or tips!

EDIT: I forgot to add the examples!

Example:

const sayHello = () => console.log('hi');
const sayGoodbye = () => console.log('bye');
const shout = () => console.log('WHAT?');
const tasks = [sayHello, sayGoodbye, shout];
const delays = [500, 200, 900];

const timeoutObjs = batchTimeouts(tasks, delays); 
// should print: 
//  'bye' after 200 ms
//  'hi' after 500 ms
//  'WHAT?' after 900 ms

console.log(timeoutObjs); // [ Timeout {...},  Timeout {...}, Timeout {...} ]

CodePudding user response:

Does this work? Just create an array with the timeouts and return it.

function batchTimeouts(callbacks, delays) {
  const timeouts = [];
  for(let i = 0; i < 3; i  ){
    timeouts.push(setTimeout(callbacks[i], delays[i]));
  }
  return timeouts;
}

const sayHello = () => console.log('hi');
const sayGoodbye = () => console.log('bye');
const shout = () => console.log('WHAT?');
const tasks = [sayHello, sayGoodbye, shout];
const delays = [500, 200, 900];

const timeoutObjs = batchTimeouts(tasks, delays);
console.log(timeoutObjs); 

CodePudding user response:

  • I am unsure whether

const sayHello = () => console.log('hi');
const sayGoodbye = () => console.log('bye');
const shout = () => console.log('WHAT?');
const tasks = [sayHello, sayGoodbye, shout];
const delays = [500, 200, 900];

const timeoutObjs = batchTimeouts(tasks, delays);

function batchTimeouts(tasks, delays) {
  return tasks.map((task, index) => {
    setTimeout(task, delays[index]);
    const obj = [
      task,
      delays[index]
    ]
    return obj;
  })
};

console.log(timeoutObjs);

it's the solution you are looking for or not but here is my idea. Any senior dev feels free to edit with a correct or better solution.

  • All you need to do is create a function then just loop through a number of tasks and use its index to point out the delays use the map() function of the array which returns a new array.
  • Related