Cer*_*nce 10

你需要函数以某种方式具有状态(或使用外部变量) - 例如,你可以有一个计数器,每次调用函数时递增该计数器,如果计数器模3是0,则打印文本.

const fn = (() => {
  let count = 0;
  return () => {
    count++;
    if (count % 3 === 0) console.log('Hello World');
  };
})();
fn();
fn();
console.log('about to call for third time');
fn();
Run Code Online (Sandbox Code Playgroud)

另一种选择是在count外面fn,例如:

let count = 0;
function fn() {
  count++;
  if (count % 3 === 0) console.log('Hello World');
}
fn();
fn();
console.log('about to call for third time');
fn();
Run Code Online (Sandbox Code Playgroud)

但这不是自足的,count然后可以被你不想要的同一范围内的其他东西修改,因此也就是IIFE.