<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<button id="jieliu">
节流按钮
</button>
<script>
function fn() {
console.log(Date.now())
}
function jieliu(fn, delay = 2000) {
let oldTime = Date.now();
return function () {
let newTime = Date.now()
if (newTime - oldTime >= delay) {
fn.apply(null)
oldTime = Date.now();
}
}
}
function jieliu2(fn, delay = 1000) {
let timer = null;
return function () {
if (!timer) {
timer = setTimeout(() => {
fn.apply(null)
timer = null
}, delay)
}
}
}
function jieliu3(fn, delay = 2000) {
let timer = null
let starttime = Date.now()
return function () {
let curTime = Date.now()
let remaining = delay - (curTime - starttime)
clearTimeout(timer)
if (remaining <= 0) {
fn.apply(null)
starttime = Date.now()
} else {
timer = setTimeout(fn, remaining)
}
}
}
function fandou(fn, delay=100) {
let timer;
return function () {
clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(null)
}, delay)
}
}
// let a = jieliu(fn)
let a = fandou(fn)
document.getElementById("jieliu").onclick = function () {
a()
// console.log(22222222)
}
// var b = setTimeout(() => {
// }, 2000)
// console.log("b:" + b)
</script>
</body>
</html>
防抖与节流总结
最新推荐文章于 2025-05-06 18:27:06 发布