前端闲聊

317 阅读1分钟

1.封装一个localStorage, 保证数据的时效性

代码

    const set = (key, value) => {
      const curTime = new Date().getTime();
      localStorage.setItem(key, JSON.stringify({ data: value, time: curTime }));
    };
    const get = (key, exp) => {
      const localData = localStorage.getItem(key);
      if (!localData) return "";
      const localDataObj = JSON.parse(localData);
      const nowTime = new Date().getTime();
      const localDataTime = localDataObj.time || nowTime;
      if (nowTime - localDataObj.time > exp) {
        console.log("数据已过期");
        // 删除
        localStorage.removeItem(key);
        return false;
      } else {
        if (!localDataObj.data) return "";
        const data = JSON.parse(localDataObj.data);
        return data;
      }
    };

调用

const value = '{"name":"yd"}';
set("info", value);
get("info", 1000); // 过期时间为1秒
get("info", 1000 * 60 * 60); // 过期时间为1分钟

2.简单的js防抖和节流

1.防抖(debounce)(短时间内大量触发同一事件,只会执行一次函数)

实现:实现的关键就在于setTimeout这个函数,由于还需要一个变量来保存计时,考虑维护全局纯净,可以借助闭包来实现

   function debounce(fn,delay){
      let timer = null //借助闭包
      return function() {
          if(timer){
              clearTimeout(timer) 
          }
          timer = setTimeout(fn,delay) // 简化写法
      }
  }

2.节流(throttle)(短时间内大量触发同一事件,那么在函数执行一次之后,该函数在指定的时间期限内不再工作,直至过了这段时间才重新生效。)

```bash
 function throttle(fn,delay){
    let valid = true
    return function() {
       if(!valid){
           //休息时间 暂不接客
           return false 
       }
       // 工作时间,执行函数并且在间隔期内把状态位设为无效
        valid = false
        setTimeout(() => {
            fn()
            valid = true;
        }, delay)
    }
}