Skip to content

Commit

Permalink
feat: 节流
Browse files Browse the repository at this point in the history
  • Loading branch information
happyCoding1024 committed Sep 3, 2024
1 parent a24b7b0 commit 86864ae
Showing 1 changed file with 20 additions and 15 deletions.
35 changes: 20 additions & 15 deletions 面试/手撕代码练习/节流.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,26 +7,18 @@
<title>节流</title>
</head>
<body>
<div id="container">hello</div>
<div>hello</div>
<div>hello</div>
<div>hello</div>
<div>hello</div>
<div>hello</div>
<div>hello</div>
<div id="container" draggable="true" style="width: 100px; height: 100px; background-color: antiquewhite;">hello</div>

<script>

// 写法 1
function throttle1(fn, duration) {
let timer = null;
return function () {
console.log('function this === ', this);
return function() {
if (timer) {
return;
}

timer = setTimeout(() => {
// 使用arguments外面return后面就不用要箭头函数
fn.apply(this, arguments);
timer = null;
}, duration);
Expand All @@ -50,11 +42,24 @@
}
}

const cbThrottle = throttle2(function () {
console.log(this);
}, 1000);
const containerElem = document.getElementById("container")
containerElem.addEventListener('drag', throttle2((e) => {
console.log('回调中的this === ', this)
console.log("拖动事件 e === ", e)
}))

document.addEventListener('scroll', cbThrottle);
function throttle(fn, duration) {
let timer = null

return function () {
if (timer) return

timer = setTimeout(() => {
fn.apply(this, arguments)
timer = null
})
}
}
</script>
</body>
</html>

0 comments on commit 86864ae

Please sign in to comment.