只执行一次的ONCE函数

618 阅读1分钟

利用闭包,once函数可以防止函数不必要的重复执行,只让其执行一次。在一些用户提交事件中可以使用,处理接口抛出同一个异常时也可以使用。

function once(fun, obj) {
  let count = 0;
  let result;
  return function () {
    count += 1;
    if (obj === undefined) {
      obj = {};
    }
    if (count === 1) {
      result = fun.apply(obj, [...arguments]);
    }
    return result;
  };
}

使用示例

const print = once(() => {
  console.log('1');
}, this);
const add = once((x, y) => x + y);
console.log(add(1, 2));
console.log(add(1, 2)); // 只执行一次add
print();
print(); // 只打印一次'1'