[Medium] Implement repeate function

March 7, 2024

☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee

Question Prompt

Implement repeat function which is a higher-order function that takes three parameters:

  • func: The function to be repeated.
  • times: The number of times to repeat the function.
  • wait: The interval in milliseconds between each repetition.

The repeat function returns an executable function that, when executed, will repeatedly execute the func function times times, with a wait millisecond interval between each execution.

const func = () => console.log("Hello, world!");
const repeatFunc = repeat(func, 3, 1000);

// print "Hello, world!" to the console three times
// with a one-second interval between each print
repeatFunc();

Solutions

Looking to practice more questions like these? We recommend GreatFrontEnd, the best platform for honing your frontend interview skills!

The repeat function can be implemented using the concept of closures. A closure is a function that retains the values of variables from the scope in which it was created. This allows us to access the parameters func, times, and wait. Accessing times allows us to count how many times the function has been called.

In repeat, we return a wrapper function. In the returned wrapper function, if times is greater than 0, then the function can still be called repeatedly. So at this point, the func function is called, and setTimeout is used to call the wrapper function again after wait milliseconds. And each time it is called, times is decremented.

function repeat(func, times, wait) {
  // repeat will return a function
  return wrapper function(...args) {
    // if times still remain
    if (times > 0) {
      // execute the function
      func(...args);
      // after times, call the wrapper function with ...args again
      setTimeout(wrapper, wait, ...args);
      // times minus 1
      times--;
    }
  }
}
☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee