前端节流与防抖

86 阅读1分钟

当频繁出发事件时可以让节流只触发一次 immediate的意思是第一次就触发然后

function debounce () { var timer; return function (fn, wait, immediate) { var content = this; var args = arguments; if (timer) clearTimeout(timer); if (immediate) { //第一次触发 const isExecute = !timer timer = setTimeout(function () { timer = null }) if (isExecute) fn.apply(content, arguments) } else { timer = setTimeout(function () { fn.apply(content, arguments) },wait) } } }

image.png