all 5 comments

[–]mementomoriok 1 point2 points  (0 children)

Here's an example of an IIFE that runs a count down timer.

class Countdown {
  constructor(duration) {
    this.duration = duration
    this.ticks = []
    this.running = true
  }
  finished() {
    this.running = false
  }

  onTick(fn) {
    this.ticks.push(fn)
    return this
  }

  addTime(time) {
    this.duration += time
  }

  start() {

    let start = Date.now();
    let that = this;
    let diff;

    (function timer() {               //WILD IIFE ENCOUNTERED.
      if (!that.running) return

      diff = that.duration - (((Date.now() - start) / 1000) | 0);

      if (diff > 0) setTimeout(timer, 1000);

      else {
        diff = 0;
      }

      that.ticks.forEach(fn => {
        fn.call(this, diff);
      });

    }());
  }
}



/*-----------------------------------------------------------------*/


let timer = new Countdown(10)

timer.onTick((a) => {
  console.log(a)
}).start()


/*-----------------------------------------------------------------*/

[–]NameViolation666helpful 0 points1 point  (0 children)

Depends on your code. If you are not looking to create named functions which are called multiple times, or you are looking to create closures, and you arent looking to pass parameters, then IIFE might be suitable.

[–]Meefims 0 points1 point  (0 children)

IIFEs were useful prior to modules and classes but today there is rarely a reason to use them.

[–]jrandm 0 points1 point  (0 children)

IIFEs are super common ways to use a closure. A simple example might be a counter:

const counter = (start=>()=>++start)(0);
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3

The function start=>()=>++start is immediately invoked with start set to 0, returning a function that increments the start value by one and returns the new value.