防抖(debounce)和节流(throttle)函数之节流函数

tech2022-07-13  142

 上篇博客写到,防抖函数是在规定的一段事件内,只执行一次函数,那要是用户一直拖着鼠标滚来滚去,理论上来说就一直不会输出距离顶部的距离,那么要是产品提个需求,就算用户不断的拖着滚动条,也能每过一段事件就输出一次距离顶部的距离呢?  这个就是就要用到我们的节流函数了

function top() { let top = document.documentElement.scrollTop console.log(`滚动条的位置:${top}`) }; function throttle(fn, wait) { var lastTime = null return function() { var nowTime = new Date().getTime() if (nowTime - lastTime > wait) { fn() lastTime = nowTime } } } window.onscroll = throttle(top, 1000)

实现节流的方法不止时间戳一么一种,还可以借助计时器的状态和判断计时器的返回值来实现,原理其实都差不多

最新回复(0)