防抖(输入框多次输入,并且监听)一直输入,隔一段时间再响应
![](https://img.haomeiwen.com/i1707358/ba94e7e805462af1.png)
节流 (提交表单)一直点击,一段时间只响应一次
![](https://img.haomeiwen.com/i1707358/23f563875fbe5c4d.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'
网友评论