1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
- <!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: 200px;
- height: 200px;
- color: #ff0;
- font-size: 30px;
- font-weight: 800;
- text-align: center;
- line-height: 200px;
- background: #f00;
- }
- </style>
- </head>
- <body>
- <div id="box"></div>
- <!--
- 节流:
- 限制函数在一定时间内的执行次数
- 规定n秒内连续点击事件但只执行一次
- 鼠标移动 鼠标跟踪 窗口大小 频繁点击按钮
- 在固定时间间隔内,函数最多只执行一次。无论事件触发多少次,都保证在指定时间内只执行一次。
- -->
- <script>
- var box = document.getElementById("box");
- console.log(box, box.innerHTML)
- // count +1
- let i = 1
- function Count() {
- box.innerText = i++;
- }
- function throttle(fn, delay) {
- var timer = null;
- return function () {
- if (!timer) {
- timer = setTimeout(function () {
- fn();
- timer = null;
- }, delay)
- }
- }
- }
- box.addEventListener('click', throttle(Count, 3000))
- /**
- * 防抖与节流的区别:
- * 节流 保证函数在固定时间间隔内至少执行一次
- * 防抖 在事件停止触发一段时间后才执行
- */
- </script>
- </body>
- </html>
|