函数节流 减少被调用的次数,让其在规定的时间内只调用一次
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>节流函数的实现</title> <style> html, body{ height: 500%; } </style> </head> <body> <script> /* fn 传入的函数 deplay 规定的时间 */ function throttle(fn,delay){ // 记录上一次触发时间 var lastTime = Date.now(); return function(){ // 记录当前函数的触发时间 var nowTime = Date.now(); if(nowTime - lastTime > delay){ // 将this指回fn fn.call(this); // 同步时间 lastTime = nowTime; } } } document.onscroll = throttle(()=>{console.log("调用节流函数"+Date.now()) },200) </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>防抖函数</title> </head> <body> <button>点击</button> <script> /* fn 调用的函数 deplay 规定延迟多久后调用 */ function debounce(fn,deplay){ // 记录上一次的延时器 var timer = null; return function(){ // 清除上一次的延时器 clearTimeout(timer); // 设置新的延时器 timer = setTimeout(function(){ fn.apply(this); },deplay) } } document.querySelector("button").onclick = debounce(()=>{console.log("点击事件被触发了"+Date.now());},200); </script> </body> </html>