<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
<script>
//防抖
function debounce(fn, wait) {
var timeout = null;
return function () {
if (timeout !== null)
clearTimeout(timeout);
timeout = setTimeout(fn, wait);
}
}
// 處理函數
function handle() {
console.log(Math.random());
}
// 滾動事件
window.addEventListener('scroll', debounce(handle, 1000));
</script>
<script>
//節流
var throttle = function (func, delay) {
var prev = Date.now();
return function () {
var context = this;
var args = arguments;
var now = Date.now();
if (now - prev >= delay) {
func.apply(context, args);
prev = Date.now();
}
}
}
function handle() {
console.log(Math.random());
}
window.addEventListener('scroll', throttle(handle, 1000));
</script>
</html>
防抖就是防止事件頻繁觸發,針對最后一次觸發才執行函數
節流就是只在單位的時間內才觸發該事件
防抖 節流 的好處就是防止過分的觸發事件執行函數,導致瀏覽器性能降低或者體驗不好