5、工具函数

getQueryString

const url = "https://www.baidu.com/s?id=123&name=why&phone=13876769797";

function getQueryString(url) {
  const index = url.indexOf("?");
  // 无参数直接返回
  if (index === -1) return undefined;
  const result = {};
  // 截取参数
  const str = url.substr(index + 1);
  // 切割参数
  const strArr = str.split("&");
  // 遍历赋值
  strArr.forEach((item) => {
    const [key, value] = item.split("=");
    result[key] = value;
  });
  return result;
}

const query = getQueryString(url);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

防抖

function debounce(fn, delay) {
  let timer = null;
  /// 返回函数,不能用箭头函数,会导致参数丢失
  return function () {
    // 绑定this
    const ctx = this;
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      // 注意传参
      fn.call(ctx, ...arguments);
    }, delay || 300);
  };
}

function clickHandle(e) {
  console.log(e, this);
}

document.documentElement.addEventListener("click", debounce(clickHandle, 500));

document.documentElement.addEventListener(
  "click",
  debounce(function (e) {
    console.log(e, this);
  }, 500)
);

// 这样使用拿不到this
document.documentElement.addEventListener(
  "click",
  debounce((e) => {
    console.log(e, this);
  }, 500)
);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

节流

function throttle(fn, delay, first) {
  let timer = null;
  let firstCango = first;
  return function () {
    const ctx = this;

    // 第一次是否要不节流直接执行
    if (firstCango) {
      firstCango = false;
      fn.call(ctx, ...arguments);
    }

    if (timer) {
      return;
    } else {
      timer = setTimeout(() => {
        // 清空定时器
        clearTimeout(timer);
        timer = null;
        fn.call(ctx, ...arguments);
      }, delay || 300);
    }
  };
}

function clickHandle(e) {
  console.log(e, this);
}

document.documentElement.addEventListener("click", throttle(clickHandle, 500));

document.documentElement.addEventListener(
  "click",
  throttle(function (e) {
    console.log(e, this);
  }, 500)
);

document.documentElement.addEventListener(
  "click",
  throttle((e) => {
    console.log(e, this);
  }, 500)
);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44