FE-Interview icon indicating copy to clipboard operation
FE-Interview copied to clipboard

节流

Open lgwebdream opened this issue 5 years ago • 4 comments

lgwebdream avatar Jul 06 '20 16:07 lgwebdream

扫描下方二维码,获取答案以及详细解析,同时可解锁800+道前端面试题。

lgwebdream avatar Jul 06 '20 16:07 lgwebdream

function throttle(fn, delay) {
  let called = false
  return function() {
    if (!called) {
      called = true
      setTimeout(() => {
        fn.apply(this, arguments)
        called = false
      }, delay)
    }
  }
}

523451928 avatar Jul 16 '20 09:07 523451928

function throttle(func, wait) {
  let context, arges;
  let prevous = 0;

  return function () {
    let now = new Date();
    context = this;
    arges = arguments;
    if (now - prevous > wait) {
      func.apply(context, arges);
      prevous = now;
    }
  };
}

future-builder007 avatar Jul 29 '20 06:07 future-builder007


function throttle(executer, wait, ...defaultParams) {
  let token = true;

  return function throttleWrappedExecuter(...args) {
    if (!token) {
      return;
    }
    token = false;
    setTimeout(() => {
      executer.call(this, ...defaultParams, ...args);
      token = true;
    }, wait);
  };
}

const printHello = throttle(
  (...args) => {
    console.log("hello", ...args);
  },
  5000,
  "DEV"
);

image

gaohan1994 avatar Apr 29 '24 09:04 gaohan1994