<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<button οnclick="debounce(fun,2000)()">函数防抖</button>
<button οnclick="throttle(fun1,2000)()">函数节流</button>
</body>
</html>
<script type="text/javascript">
// 函数防抖
var timer = null;
function debounce(fn, delay) {
return function() {
var _this = this;
var _arg = arguments;
clearInterval(timer);
timer = setTimeout(function() {
fn.apply(_this, _arg)
}, delay)
}
}
function fun() {
console.log("函数防抖")
}
// 函数节流
var lasttime = 0;
function throttle(fn, wait) {
return function() {
var nowtime = new Date().getTime();
if (nowtime - lasttime > wait) {
fn.apply(this, arguments);
lasttime = nowtime;
}
}
}
function fun1() {
console.log("函数节流")
}
</script>