校园网建设网站特色网络营销的优化和推广方式
某些事件中(如 onresize onscroll onkeydown onkeyup onmousemove …),会连续触发函数的执行,如果函数执行一些耗时的操作(如请求数据…),会影响性能,也有可能造成服务器压力。这时可以用 防抖函数 或 节流函数解决这种问题。
防抖函数:
不管事件怎么连接触发函数的执行,我只在事件结束后的N毫秒执行一次函数;如果事件还在连接触发,就不执行函数。
<!DOCTYPE html>
<html>
<head><title></title><meta charset="utf-8" /><style type="text/css">#box{width:200px;height:200px;border: 1px solid red;}</style>
</head>
<body><div id="box"></div></body>
<script>
function debounce(fn,wait){let timeoutId = null;return function(){let args = arguments;timeoutId && clearTimeout(timeoutId);timeoutId = setTimeout(function(){fn(args);},wait)}
}
function doing(arg){console.log(arg);
}
let fn = debounce(doing,1000);
box = document.getElementById("box");
box.onmousemove = function(){fn(1,2,3);
}
</script>
</html>
效果图:
节流函数:
事件在连接触发的过程中,我会隔N毫秒执行一次函数;如果N毫秒内多次触发事件,则只会执行一次函数。
<!DOCTYPE html>
<html>
<head><title></title><meta charset="utf-8" /><style type="text/css">#box{width:200px;height:200px;border: 1px solid red;}</style>
</head>
<body><div id="box"></div></body>
<script>
function throttle(fn,wait){let timeoutId = null;return function(){let args = arguments;let now = Date.now();if(!timeoutId){timeoutId = setTimeout(function(){timeoutId = null;fn(args);},wait)}}
}function doing(arg){console.log(arg);
}
let fn = throttle(doing,1000);
box = document.getElementById("box");
box.onmousemove=function(){fn(1,2,3);
}
</script>
</html>
效果图:
自己体会一下 防抖函数 和 节流函数 的区别吧。
可以根据 效果图 体会体会。
体会不明白的,自己去写一下,运行试试了。
防抖函数的应用场景:建议百度一下。懒得写。
节流函数的应用场景:建议百度一下。懒得写。
---- 结束 ----
仅学习。