| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- <!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: 90vw;
- height: 100px;
- margin:50px auto;
- background: #aaa;
- text-align: center;
- line-height: 100px;
- font-size: 50px;
- color: #fff;
- font-weight: bold;
- }
- </style>
- </head>
- <body>
- <!-- 防抖节流函数 -->
- <!-- 防抖函数:在事件触发后等待一段时间,只执行一次函数 如果事件触发后在等待时间内再次触发则清除上一次时间再次等待 -->
- <!-- 节流函数:在事件触发后等待一段时间,只执行一次函数 如果事件触发后在等待时间内再次触发则在等待时间内不执行函数 -->
- <div class="box" id="box1">0</div>
- <div class="box" id="box2">0</div>
- <div class="box" id="box3">0</div>
- <script>
- let box1 = document.getElementById('box1');
- let box2 = document.getElementById('box2');
- let box3 = document.getElementById('box3');
- // 普通事件
- box1.onmousemove = function(){
- this.innerText = Number(this.innerText) + 1;
- }
- // 防抖函数
- // 两个参数 第一个参数是函数(到时间了要干什么) 第二个参数是等待时间
- function debounce(fn,t){
- let timer = null;
- return function(){
- if(timer){
- clearTimeout(timer);
- }
- timer = setTimeout(()=>{
- fn();
- },t);
- }
- }
- box2.onmousemove = debounce(function(){
- box2.innerText = Number(box2.innerText) + 1;
- },1000);
- // 节流函数
- // 两个参数 第一个参数是函数(到时间了要干什么) 第二个参数是等待时间
- function throttle(fn,t){
- let timer = null;
- return function(){
- if(timer){
- return;
- }
- timer = setTimeout(()=>{
- fn();
- timer = null;
- },t);
- }
- }
- box3.onmousemove = throttle(function(){
- box3.innerText = Number(box3.innerText) + 1;
- },1000);
- </script>
- </body>
- </html>
|