<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js"></script>
<title>节流和防抖</title>
</head>
<body>
<ul>
<li>防抖(debounce):无论执行多少次都以最后一次为准(电脑自动休眠就是经典的防抖)</li>
<li>节流(throttle):调用了多次只要第一次调用有效( 单位时间内多次触发函数,也只有一次生效 )</li>
</ul>
<button id="debounce">防抖</button>
<button id="throttle">节流</button>
<script>
function move(e) {
var that = $(e.target);
console.log(that.attr("id"));
console.log("Hello World!");
}
function debounce(fn) {
var debItem = null
return function() {
var arg = arguments[0]
if (debItem) {
clearTimeout(debItem)
}
debItem = setTimeout(function() {
fn(arg)
}, 1000);
}
}
function throttle(fn) {
var thrItem = null
return function() {
var arg = arguments[0]
if (thrItem) {
return
}
thrItem = setTimeout(function() {
fn(arg)
thrItem = null
}, 1000);
}
}
$(document).ready(function() {
$("#debounce").on('click', debounce(move));
$("#throttle").on('click', throttle(move));
});
</script>
</body>
</html>