函数抖动:在高频操作时,不立即执行被执行函数,当高频操作停止时执行函数操作(例如:快速滚动滚动条,滚动条事件在停止滚动时执行)
函数节流:在高频操作时,函数会在一段时间内执行一次(例如:地铁,每站停止时间固定,到点都会开动,不会随乘客流而一直停留)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>防抖动实现</title>
<style>
body{
height: 5000px;
}
</style>
</head>
<body>
<script type="text/javascript">
// 防抖动实现
function debounce(fn, wait) {
var timeout = null;
return function() {
if(timeout !== null){
console.log("清除");
clearTimeout(timeout);
}
timeout = setTimeout(fn, wait);
}
}
// 滚动事件
setInterval(debounce(test,800),1200)
// 节流(时间戳)
function throttle(fn,delay){
var prev = Date.now();
return function() {
var _this = this;
var args = arguments;
var now = Date.now();
if (now - prev >= delay) {
fn.apply(_this, args);
prev = Date.now();
}
}
}
// 节流(定时器)
function throttle(fn,delay){
var timer = null;
return function(){
var _this = this;
var args = arguments;
if (!timer) {
timer = setTimeout(function() {
fn.apply(_this, args);
timer = null;
}, delay);
}
}
}
function throttle(fn,delay){
var timer = null;
var startTime = Date.now();
return function() {
var curTime = Date.now();
var tempTime = delay - (curTime - startTime);
var _this = this;
var args = arguments;
clearTimeout(timer);
if (tempTime <= 0) {
fn.apply(_this, args);
startTime = Date.now();
} else {
timer = setTimeout(fn, tempTime);
}
}
}
setInterval(throttle(test,3000),200)
// 处理函数
function test() {
console.log("测试函数!!!");
}
</script>
</body>
</html>