函数节流(Throttling)
函数节流应用的实际场景,多数在监听页面元素滚动事件的时候会用到。因为滚动事件,是一个高频触发的事件。以下是监听页面元素滚动到底部的示例代码:
// 简单的节流函数
function throttle(func, wait, mustRun) {
var timeout,
startTime = new Date();
return function() {
var context = this,
args = arguments,
curTime = new Date();
clearTimeout(timeout);
// 如果达到了规定的触发时间间隔,触发 handler
if (curTime - startTime >= mustRun) {
func.apply(context, args);
startTime = curTime;
// 没达到触发间隔,重新设定定时器
} else {
timeout = setTimeout(func, wait);
}
};
};
// 实际想绑定在 scroll 事件上的 handler
function realFunc() {
//判断是否滚动到页面最底部
var scrollTop = Math.ceil($(this).scrollTop());
var scrollHeight = $(document).height();
var windowHeight = $(this).height();
if (scrollTop + windowHeight >= scrollHeight) {
$("script:first").before("<p>Lorem ip.</p>")
}
}
// 采用了节流函数
$(window).scroll(throttle(realFunc, 500, 1000))