我们了解了函数防抖与函数节流的思路后, 我们现在来将他们封装起来, 提高代码复用性.
今天直接上菜
cb 要处理防抖的函数
time 默认的高频间隔时间
isStart 是否在头部执行
函数防抖封装: 调用 debounce 函数, 返回一个处理过防抖的函数
- <!DOCTYPE html>
- <HTML lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>
- Document
- </title>
- <style>
- #box { width: 300px; height: 400px; background: red; }
- </style>
- </head>
- <body>
- <div id="box">
- </div>
- <script>
- function debounce(cb, delay = 200, isStart = false) {
- let timer = 0;
- let isFirst = true; // 是否是第一次执行
- return function(...arg) {
- clearTimeout(timer);
- if (isFirst && isStart) {
- cb.apply(this, arg);
- isFirst = false;
- }
- timer = setTimeout(() = >{ (!isStart) && cb.apply(this, arg);
- isFirst = true;
- },
- delay)
- }
- }
- box.onmousemove = debounce((e) = >{
- console.log(1);
- },
- 200, true);
- </script>
- </body>
- </HTML>
函数节流封装:
- <!DOCTYPE HTML>
- <HTML lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>
- Document
- </title>
- <style>
- #box { width: 300px; height: 400px; background: red; }
- </style>
- </head>
- <body>
- <div id="box">
- </div>
- <script>
- function throttle(cb, interval = 200, isStart = false) {
- let timer = 0;
- return function(...arg) {
- if (timer) {
- return;
- }
- isStart && cb.apply(this, arg);
- timer = setTimeout(() = >{ (!isStart) && cb.apply(this, arg);
- timer = 0;
- },
- interval)
- }
- }
- box.onmousemove = throttle(function(e) {
- console.log(1, e, this);
- },
- 500)
- </script>
- </body>
- </HTML>
以上的封装都是可以直接使用的, 有兴趣的看上一篇文章了解函数防抖与函数节流的思路会更好.
移动端到此也就告一段落了.
来源: https://www.cnblogs.com/jfen625/p/12563153.html