Skip to content

常用工具函数

日期格式化函数

javascript
// 封装日期格式化函数
const date = new Date('2021-4-12 10:22:22');
function dateFormat(date, format = 'YYYY-MM-DD HH:mm:ss') {
    const config = {
        YYYY: date.getFullYear(),
        MM: (date.getMonth() + 1).toString().padStart(2, 0),
        DD: date.getDate().toString().padStart(2, 0),
        HH: date.getHours().toString().padStart(2, 0),
        mm: date.getMinutes().toString().padStart(2, 0),
        ss: date.getSeconds().toString().padStart(2, 0)
    }
    for(const key in config){
        format = format.replace(key, config[key])
    }
    return format
}
console.log(dateFormat(date)); // 2021-4-12 10:22:22
console.log(dateFormat(date, 'YYYY年MM月DD日')); // 2021年4月12日
console.log(dateFormat(date, 'YYYY年MM月DD日 HH时mm分ss秒')); // 2021年4月12日 10时22分22秒

防抖 节流

防抖 debounce

每次事件触发后总是等待一段时间执行,如果在等待时间内事件再次触发,则重新计算等待时间(停止触发的时候只会执行一次,最后一次生效)

javaScript

function debounce(fun, wait) {
  let timer = null
  return (...args) => {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fun.apply(this, args)
    }, wait)
  }
}

TS 版本

typescript
function debounce(func: Function, delay: number, immediate = false): Function {
  let timer: number | undefined

  return function(this: unknown, ...args: any[]) {
    if (immediate) {
      func.apply(this, args) // 确保引用函数的指向正确,并且函数的参数也不变
      immediate = false
      return
    }
    clearTimeout(timer)
    timer = setTimeout(() => {
      func.apply(this, args)
    }, delay)
  }
}

立即执行版本

javascript
/**
* @desc 函数防抖---立即执行
* @param func 需要执行的函数
* @param wait 延迟执行时间(毫秒)
* @param immediate---true 表立即执行,false 表非立即执行
**/
function debounce(func, wait, immediate) {
    let timer;

    return function () {
        //this指向debounce
        let context = this;
        //即参数,func,wait
        let args = arguments;

        //如果timer不为null, 清除定时器
        if (timer) clearTimeout(timer);

        //如果是立即执行
        if (immediate) {
            //定义callNow = !timer
            var callNow = !timer;
            //定义wait时间后把timer变为null
            //即在wait时间之后事件才会有效
            timer = setTimeout(() => {
                timer = null;
            }, wait)
            //如果callNow为true,即原本timer为null
            //那么执行func函数
            if (callNow) func.apply(context, args)
        } else {
            //如果是不立即执行
            //那就是每次重新定时
            timer = setTimeout(function () {
                func.apply(context, args)
            }, wait);
        }
    }
}

节流 throttle

连续触发事件但在n秒内只执行一次函数

javaScript
function throttle(fun, wait) {
  let timer = null
  return (...args) => {
    if (!timer) {
      timer = setTimeout(() => {
        fun.apply(this, args)
        timer = null
      }, wait)
    }
  }
}

function throttle(fun, wait) {
  let pre = 0
  return (...args) => {
    const now = Date.now()
    if (pre - now > wait){
      fun.apply(this, args)
      pre = now
    }
  }
}

注: fun.apply(this, args)都可使用fun.call(this, ...args)替换