美文网首页
防抖节流

防抖节流

作者: 艾希_可可 | 来源:发表于2024-04-10 11:55 被阅读0次

防抖(输入框多次输入,并且监听)一直输入,隔一段时间再响应

截屏2024-04-11 11.51.24.png

节流 (提交表单)一直点击,一段时间只响应一次

截屏2024-04-11 11.46.14.png

/**

  • @desc 防抖函数,多次触发,只执行一次,适合input时时搜索
  • @param fn 目标函数
  • @param wait 延迟执行毫秒数
    /
    export function debounce(fn, wait = 500) {
    let timer = null
    return function() {
    const now = !timer
    timer && clearTimeout(timer)
    timer = setTimeout(() => {
    timer = null
    }, wait)
    if (now) {
    fn.apply(this, arguments)
    }
    }
    }
    /
    *
  • @desc 节流函数,频繁触发,间隔一段时间才能再次触发,适合button点击
  • @param fn 目标函数
  • @param wait 延迟执行毫秒数
    */
    export function throttle(fn, wait = 500) {
    let last = 0
    return function() {
    const now = Date.now()
    if (now - last > wait) {
    fn.apply(this, arguments)
    last = now
    }
    }
    }
    使用
updateCameraView: debounce((element, mapboxs) => {
      const bearing = ((-element.carStateView.carState.rotation.z + Math.PI / 2) / Math.PI) * 180
      mapboxs.flyTo({
        center: element.carStateView.carState.arrayPosition.position,
        zoom: 21,
        speed: 1,
        pitch: 70,
        bearing: bearing
      })
    }, 50),

也可以使用loadsh
import { debounce } from 'loadsh'

部分参考 https://www.zhihu.com/question/280852975

相关文章

网友评论

      本文标题:防抖节流

      本文链接:https://www.haomeiwen.com/subject/cfnxwltx.html