<!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>
#wrapper {
width: 100%;
height: 200px;
line-height: 200px;
text-align: center;
color: #fff;
background-color: #444;
font-size: 30px;
}
</style>
</head>
<body>
<div id="wrapper"></div>
<script>
var count = 1;
var oDiv = document.getElementById("wrapper");
function getUserAction(e) {
console.log('e',e);
oDiv.innerHTML = count++;
}
function debounce(fn, wait,immediate) {
var timer;
return function () {
var _this = this;
var arg = arguments
clearTimeout(timer);
if(immediate) {
var callNow = !timer
timer =setTimeout(()=>{
timer = null
},wait)
if(callNow) fn.apply(_this,arg)
} else {
timer = setTimeout(()=>{
fn.apply(_this,arg)
},wait);
}
};
}
oDiv.onmousemove = debounce(getUserAction, 1000,false);
</script>
</body>
</html>