鼠标的mousemove、scroll,浏览器窗口的resize事件等,都是在短时间内重复触发。以onresize事件为例,若事件处理程序需要进行修改元素宽度高度等操作,那么频繁的触发事件会导致频繁的重绘页面。
DOM操作比非DOM交互需要更多的内存和CPU时间,连续尝试进行过多的DOM相关操作可能会导致浏览器挂起,有时候甚至会崩溃。为了解决这个问题,需要使用定时器对该函数进行节流。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| <!DOCTYPE html >
<html lang ="en">
<head >
<meta charset ="UTF-8">
<title >scroll -滚动节流 </title >
</head >
<style >
#box{
width : 100px ;
height : 3000px ;
}
</style >
<body >
<div id ="box"></div >
</body >
<script >
//函数节流
function throttle (fn , threshhold ) {
//声明一个变量timeout
var timeout
//实时时间
var start = new Date;
//大于 threshhold 的值 才会执行函数
var threshhold = threshhold || 160
return function () {
//存下this arguments 以及 当前时间戳 new Date() - 0
var context = this , args = arguments , curr = new Date() - 0
//总是干掉事件回调
clearTimeout (timeout )
//当前时间戳 - 上次的执行时间点 如果大于threshhold 就行执行函数
if(curr - start >= threshhold ){
//console.log("now", curr, curr - start)//注意这里相减的结果,都差不多是160左右
fn .apply (context , args ) //只执行一部分方法,这些方法是在某个时间段内执行一次
start = curr
}else{
//让方法在脱离事件后也能执行一次
timeout = setTimeout (function(){
fn .apply (context , args )
}, threshhold );
}
}
}
var mousemove = throttle (function(e ) {
if(document .compatMode == "CSS1Compat") {
console .log(document .documentElement .scrollTop );
} else {
console .log(document .body .scrollTop );
}
});
// 绑定监听
window .addEventListener ('scroll', mousemove ,false);
</script>
</html > |
「两年博客,如果觉得我的文章对您有用,请帮助本站成长」
共有 0 条评论 - JS-函数节流