函数节流(throttle.js)
var throttle = function (func, wait, options) {
var context, args, result;
var timeout = null;
var previous = 0;
if (!options) options = {};
var later = function () {
previous = options.leading === false ? 0 : Date.now();
timeout = null;
result = func.apply(context, args);
if (!timeout) context = args = null;
};
return function () {
context = this;
args = arguments;
var now = Date.now();
if (!previous && options.leading === false) previous = now;
var remaining = wait - (now - previous);
if (remaining <= 0 || remaining > wait) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
previous = now;
result = func.apply(context, args);
if (!timeout) context = args = null;
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
return result;
};
};
函数防抖(debounce.js)
var debounce = function (func, wait = 1000, immediate) {
var timeout, args, context, timestamp, result;
var later = function () {
var last = Date.now() - timestamp;
if (last < wait && last >= 0) {
timeout = setTimeout(later, wait - last);
} else {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
if (!timeout) context = args = null;
}
}
};
return function () {
context = this;
args = arguments;
timestamp = Date.now();
var callNow = immediate && !timeout;
if (!timeout) timeout = setTimeout(later, wait);
if (callNow) {
result = func.apply(context, args);
context = args = null;
}
return result;
};
};
测试(index.html)
<!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">
<title>节流防抖</title>
<style>
#root{
width: 50px;
height: 50px;
background-color: aqua;
cursor: pointer;
}
</style>
</head>
<body>
<button id="root"></button>
<script src="./debounce.js"></script>
<script>
function logger(){
console.log('logger')
}
root.addEventListener('click', debounce(logger, 1000, false))
</script>
</body>
</html>