<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>什么是函数节流?什么是函数防抖?</title> <link type="text/css" rel="stylesheet" href=" "/> <style type="text/css"> * { margin: 0; padding: 0; } html,body{ height: 800px; } </style> </head> <body> <button id="btn">怕你点坏了</button> <!-- <script type="text/javascript"> window.onload = function () { } </script> --> <script type="text/javascript"> /* 函数节流:一个函数执行一次后,只有大于设定的执行周期后才会执行第二次。 - 有个需要频繁触发函数,出于优化性能角度,在规定时间内,只让函数触发的第一次生效,后面不生效 */ /* 节流函数 @param fn 要被节流的函数 @param delay 规定的时间 */ function throttle(fn,delay){ //记录上一次函数触发的时间 var lastTime = 0; return function(){ //记录当前函数触发的时间 var nowTime = Date.now(); if(nowTime - lastTime > delay){ //修正this指向问题 //fn(); fn.call(this); //同步时间 lastTime = nowTime; } } } document.onscroll = throttle(function(){console.log('scroll滚轮事件被触发了' + Date.now());},200) /* 防抖函数:一个需要频繁触发的函数,在规定时间内,只让最后一次生效,前面的不生效 -- 其实就是怕你拼命点击(怕程序崩溃),只让最后一次点击生效 */ function debounce(fn,delay){ //记录上一次的延时器 var timer = null; return function(){ //清除上一次延时器 clearInterval(timer); //重新设置新的延时器 timer = setTimeout(function(){ fn.apply(this); },delay); } } document.getElementById('btn').onclick = debounce(function(){console.log('点击事件被触发了' + Date.now());},1000); </script> </body> </html>