<!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>
</head>
<body>
<script>
let a = `如果持续的去触发事件,每隔一段时间,只执行一次事件;`;
function throttle1(func, delay) {
let old = 0;
return function () {
let context = this;
let args = arguments;
let now = Date().now;
if (now - old > delay) {
func.apply(context, args);
old = now;
}
};
}
function throttle2(func, delay) {
let timer;
return function () {
let context = this;
let args = arguments;
if (!timer) {
timer = setTimeout(function () {
func.apply(context, args);
timer = null;
}, delay);
}
};
}
function throttle3(func, delay) {
let timer;
let old = 0;
return function () {
let context = this;
let args = arguments;
let now = Date().now;
if (now - old > delay) {
if (timer) {
clearTimeout(timer);
timer = null;
}
func.apply(context, args);
old = now;
} else if (!timer) {
timer = setTimeout(function () {
now = Date().now;
func.apply(context, args);
timer = null;
}, delay);
}
};
}
function throttle4(func, delay) {
let timer;
let old = 0;
return function () {
let context = this;
let args = arguments;
let now = Date().now;
if (now - old > delay) {
if (timer) {
clearTimeout(timer);
timer = null;
}
func.apply(context, args);
old = now;
} else if (!timer) {
timer = setTimeout(function () {
now = Date().now;
func.apply(context, args);
timer = null;
}, delay);
}
};
}
let a = `DOM元素的拖拽;射击游戏;计算鼠标移动的距离;监听scroll滚动;`;
</script>
</body>
</html>