Skip to content

常用

节流 throttle

ts
/**
 * 节流函数:单位时间内,只有一次触发事件的回调函数执行
 * @param fn
 * @param threshold ms 单位时间
 */
export function throttle(fn: (...args: any) => void, threshold = 200) {
  // 第一次立即执行
  let timer
  return (...args) => {
    if (!timer) {
      timer = setTimeout(() => {
        fn(...args)
        timer = null
      }, threshold)
    }
  }
}

function print(...args) {
  console.log(...args)
}

const t = throttle(print, 200)

t(1)
t(2)
// 输出: 1
/**
 * 节流函数:单位时间内,只有一次触发事件的回调函数执行
 * @param fn
 * @param threshold ms 单位时间
 */
export function throttle(fn: (...args: any) => void, threshold = 200) {
  // 第一次立即执行
  let timer
  return (...args) => {
    if (!timer) {
      timer = setTimeout(() => {
        fn(...args)
        timer = null
      }, threshold)
    }
  }
}

function print(...args) {
  console.log(...args)
}

const t = throttle(print, 200)

t(1)
t(2)
// 输出: 1

防抖 debounce

ts
/**
 * 防抖函数:函数被触发后 n 秒执行回调,n 秒内被触发,则重新计时
 * @param fn 执行的函数
 * @param delay ms 延迟执行时间
 */
export function debounce(fn: (...args: any) => void, delay = 200) {
  let timer = null
  return (...args) => {
    if (timer) {
      clearTimeout(timer)
      timer = null
    }

    timer = setTimeout(() => {
      fn(...args)
    }, delay)
  }
}

function print(...args) {
  console.log(...args)
}

const d = debounce(print, 200)
d(1)
d(2)
// 输出:2
/**
 * 防抖函数:函数被触发后 n 秒执行回调,n 秒内被触发,则重新计时
 * @param fn 执行的函数
 * @param delay ms 延迟执行时间
 */
export function debounce(fn: (...args: any) => void, delay = 200) {
  let timer = null
  return (...args) => {
    if (timer) {
      clearTimeout(timer)
      timer = null
    }

    timer = setTimeout(() => {
      fn(...args)
    }, delay)
  }
}

function print(...args) {
  console.log(...args)
}

const d = debounce(print, 200)
d(1)
d(2)
// 输出:2

class 链式调用

实现:

ts
const u = new U()
u.console('breakfast').setTimeout(3000).console('lunch').setTimeout(3000).console('dinner')
const u = new U()
u.console('breakfast').setTimeout(3000).console('lunch').setTimeout(3000).console('dinner')
ts
export class U {
  queue: Promise<any> = Promise.resolve()

  console(msg: string) {
    this.queue = this.queue.then(() => {
      console.log(msg)
    })
    return this
  }

  setTimeout(duration: number) {
    this.queue = this.queue.then(() => {
      return new Promise((resolve) => {
        setTimeout(resolve, duration)
      })
    })
    return this
  }
}
export class U {
  queue: Promise<any> = Promise.resolve()

  console(msg: string) {
    this.queue = this.queue.then(() => {
      console.log(msg)
    })
    return this
  }

  setTimeout(duration: number) {
    this.queue = this.queue.then(() => {
      return new Promise((resolve) => {
        setTimeout(resolve, duration)
      })
    })
    return this
  }
}