开发中的节流
开发中如果需要监听用户滚动网页我们去触发某些事件,那么必须要间隔一段时间去触发请求,不然会导致网络阻塞,
想象一下深海的蓝鲸每间隔30min出一次水面进行呼吸;
首先1. 触发事件, 2.执行任务,并且设置时间间隔,如果时间间隔内再次触发,就取消任务,4.如果时间间隔之后有触发行为,就再次执行任务和设置时间间隔
方法1:
function coloring(){ let r = Math.floor(Math.random() * 255); let g = Math.floor(Math.random() * 255); let b = Math.floor(Math.random() * 255); document.body.style.background = `rgb(${r},${g},${b})` } function throttle (func, delay){ let timer return function (){ let args = arguments; if(timer) { // 拦截,不让多次执行, 如果timer被赋值了,也就是这个时候还有函数再等待执行,那么就直接返回 (重要步骤) return } timer = setTimeout(() => { // 赋值执行任务 func.apply(this, args) timer = null // 延迟执行之后清空timer },delay) } }
方法2: 使用date
function throttle (func, delay) { let pre = 0; return function (){ let now = new Date() let context = arguments; let args = arguments; if(now - pre > delay) { func.call(context, args) pre = now } } }