Explanation of JavaScript anti shake case
- 2021-11-10 08:53:02
- OfStack
Principle
The principle of anti-shake is: although you trigger an event, I must execute it after the event triggers n seconds. If you trigger this event within n seconds triggered by an event, I will take the time of the new event as the standard and execute it after n seconds. In a word, I will not execute until you trigger the event n seconds before triggering the event.
Case
<!DOCTYPE html>
<html lang="zh-cmn-Hans">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="IE=edge, chrome=1">
<title>debounce</title>
<style>
* {
margin: 0;
padding: 0;
}
#container {
width: 100%;
height: 200px;
line-height: 200px;
text-align: center;
color: #fff;
background-color: #444;
font-size: 30px;
}
</style>
</head>
<body>
<div id="container"></div>
<script src="debounce.js"></script>
</body>
</html>
function getUserAction(e) {
console.log(this);
console.log(e);
container.innerHTML = count++;
};
function debounce(func, wait) {
var timeout;
return function () {
clearTimeout(timeout);
timeout = setTimeout(() => {
func.apply(this, arguments); // Solve this And event objects event
}, wait);
}
}
container.onmousemove = debounce(getUserAction, 1000);