Iterate n times

JavaScript, Function · Oct 20, 2020

Iterates over a callback n times.

  • Use Function.prototype.call() to call fn n times or until it returns false.
  • Omit the last argument, context, to use an undefined object (or the global object in non-strict mode).
const times = (n, fn, context = undefined) => {
  let i = 0;
  while (fn.call(context, i) !== false && ++i < n) {}
};
var output = '';
times(5, i => (output += i));
console.log(output); // 01234

More like this

  • Unfold array

    Builds an array, using an iterator function and an initial seed value.

    JavaScript, Function · Sep 15, 2020

  • Chunk iterable

    Chunks an iterable into smaller arrays of a specified size.

    JavaScript, Function · Mar 16, 2021

  • Resolve promise after given amount of time

    Creates a promise that resolves after a given amount of time to the provided value.

    JavaScript, Function · Jan 8, 2022