防抖与节流
函数防抖与节流
函数防抖(debounce) : 当持续触发事件时,一段时间内没有再次触发此事件,事件处理函数才会执行一次.如果设定的时间来到之前,又一次触发了事件,则重新刷新计算时间.
应用场景:search搜索:用户输入时用防抖来节约请求资源
鼠标不断点击触发,mousedown(单位时间内只触发一次) 监听滚动事件,比如是否滑到底部自动加载更多,用throttle来判断
// 防抖函数(debounce): 非立即执行版本
function debounce(fn, time) { var timeOut; return function () { if (timeOut) clearTimeout(timeOut); timeOut = setTimeout(fn, time) } } // 处理函数 function handel() { console.log(Math.random()) } //滚动事件 window.addEventListener('scroll', debounce(handel, 1000));
// 防抖函数(debounce): 立即执行 function debounce (func,wait) { let tiemout; return function () { let _this = this; let args = arguments; if(tiemout) clearTimeout(tiemout) let callNow =!tiemout tiemout = setTimeout(function() { tiemout = null },wait) if(callNow) func.apply(_this,args) } }
节流函数(throttle) : 当事件触发时保证一段时间内只触发一次此事件.通俗的解释就比如水龙头,打开之后水就哗哗的往下流,秉承勤俭节约的传统美德,我们要控制水的大小,最好是如我们心意控制水一滴一滴的按照某个规律往下流.节流函数主要有两种实现方法: 时间戳和定时器
// 时间戳:throttle let throttle = function(func,delay) { var prev = Date.now() return function() { var _this = this; var args = arguments var now = Date.now() if (now - perv >= delay) { func.apply(_this, args); perv = Date.now(); } } } function handle () { console.log('节流函数', Math.random()) } window.addEventListener('scroll', throttle(handle,1000)) // 定时器: throttle let throttle = function (fn, delay) { var timer = null; return function () { var _this = this; var args = arguments if (!timer) { timer = setTimeout(function () { fn.apply(_this, args) timer = null; }, delay) } } } function handle1() { console.log('节流定时器', Math.random()) } window.addEventListener('scroll', throttle(handle1, 1000))

浙公网安备 33010602011771号