Skip to content

手写防抖函数

函数防抖是指在事件被触发 n 秒后再执行回调,如果在这 n 秒内事件又被触发,则重新计时。这可以使用在一些点击请求的事件上,避免因为用户的多次点击向后端发送多次请求。

js
// 函数防抖的实现
function debounce(fn, wait) {
  let timer = null;

  return function() {
    let context = this,
        args = arguments;

    // 如果此时存在定时器的话,则取消之前的定时器重新记时
    if (timer) {
      clearTimeout(timer);
      timer = null;
    }

    // 设置定时器,使事件间隔指定事件后执行
    timer = setTimeout(() => {
      fn.apply(context, args);
    }, wait);
  };
}

手写节流函数

函数节流是指规定一个单位时间,在这个单位时间内,只能有一次触发事件的回调函数执行,如果在同一个单位时间内某事件被触发多次,只有一次能生效。节流可以使用在 scroll 函数的事件监听上,通过事件节流来降低事件调用的频率。

js
// 函数节流的实现;
// 方式1: 使用时间戳
function throttle(fn, delay) {
  let curTime = Date.now();

  return function() {
    let context = this,
        args = arguments,
        nowTime = Date.now();

    // 如果两次时间间隔超过了指定时间,则执行函数。
    if (nowTime - curTime >= delay) {
      curTime = Date.now();
      return fn.apply(context, args);
    }
  };
}
// 方式2: 使用定时器
function thorttle2(fn, wait) {
  let timer;
  return function () {
    let _this = this;
    let args = arguments;

    if (!timer) {
      timer = setTimeout(function () {
        timer = null;
        fn.apply(_this, args);
      }, wait);
    }
  };
}

时间格式化函数

js
export default function formatDate(time: Date, format = 'YYYY-MM-DD hh:mm:ss') {
  var date = new Date(time)

  var year = date.getFullYear()
  var month = date.getMonth() + 1 //月份是从0开始的
  var day = date.getDate()
  var hour = date.getHours()
  var min = date.getMinutes()
  var sec = date.getSeconds()

  var newTime = format
    .replace(/YYYY/gi, year.toString())
    .replace(/MM/gi, month < 10 ? '0' + month.toString() : month.toString())
    .replace(/DD/gi, day < 10 ? '0' + day.toString() : day.toString())
    .replace(/hh/gi, hour < 10 ? '0' + hour.toString() : hour.toString())
    .replace(/mm/gi, min < 10 ? '0' + min.toString() : min.toString())
    .replace(/ss/gi, sec < 10 ? '0' + sec.toString() : sec.toString())
  return newTime
}