Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaScript专题之跟着underscore学防抖 #16

Open
huiyiwanan opened this issue Jan 18, 2023 · 0 comments
Open

JavaScript专题之跟着underscore学防抖 #16

huiyiwanan opened this issue Jan 18, 2023 · 0 comments

Comments

@huiyiwanan
Copy link
Owner

huiyiwanan commented Jan 18, 2023

前言

防抖 - 只有等事件停止触发后 n 秒才执行函数
节流 - 持续触发的时候,每 n 秒执行一次函数

思路

  1. 场景 - 用户触发事件
  2. 效果 - 首次触发执行/首次触发不执行,停止触发几秒后实现效果
  3. 逻辑 - a. 首次触发与否;b. 常规- 触发事件 - 清空倒计时函数 - 执行倒计时函数

实现

import _ from "lodash";
import "./style.css";
function component() {
  const element = document.createElement("div");

  // lodash(目前通过一个 script 引入)对于执行这一行是必需的
  // lodash 在当前 script 中使用 import 引入
  element.innerHTML = _.join(["hello", "webpack"], " ");
  element.className = "red";
  element.style.width = "500px";
  element.style.height = "500px";
  element.style.background = "#ddd";
  element.classList.add("hello");
  let status = "0",
    timeFun = null;
  element.addEventListener("mousemove", function (e) {
    console.log("ddd", e);
    if (timeFun) clearTimeout(timeFun);
    if (status === "0") {
      status = "1";
      element.innerHTML = _.join(
        ["change" + new Date(), "初始化,执行函数"],
        " "
      );
    } else {
      timeFun = setTimeout(() => {
        element.innerHTML = _.join(["change" + new Date(), "防抖"], " ");
      }, 3000);
    }
  });
  element.addEventListener("mouseout", function (e) {
    status = "0";
    console.log(status, "out");
  });

  return element;
}

document.body.appendChild(component());

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant