函数防抖节流原文地址:https://www.cnblogs.com/youma/p/10559331.html
当持续事件发生时,一定时间内没有触发事件,时间函数才会执行一次,如果在规定的时间内,再次触发了该事件,则重新计时。也就是说,用户在规定时间内多次请求,最后只执行一次。
当持续事件发生,保证事件在一定时间内之调用一次。 函数防抖和节流的区别: 防抖时多次执行变一次,节流是多次执行变每隔一段事件执行
var throttle = function(func, delay) { var prev = Date.now(); //获取时间戳 return function() { var context = this; //this指向window var args = arguments; //获取参数 var now = Date.now(); //获取时间戳 if (now - prev >= delay) { //如果两个时间戳相减大于规定时间 则执行 func.apply(context, args); //改变方法的this指向,并拆地参数 prev = Date.now(); } } } function handle() { console.log(Math.random()); } window.addEventListener('scroll', throttle(handle, 1000)); 这个节流函数利用时间戳让第一次滚动事件执行一次回调函数,此后每隔1000ms执行一次,在小于1000ms这段时间内的滚动是不执行的利用定时器:每隔一秒触发一次
var throttle = function(func, delay) { var timer = null; // 每次进入 都会清除定时器 return function() { var context = this; var args = arguments; if (!timer) { timer = setTimeout(function() { func.apply(context, args); timer = null; }, delay); } } } function handle() { console.log(Math.random()); } window.addEventListener('scroll', throttle(handle, 1000));