应用场景
- 实时输入检测:如根据用户输入文本来实时查询数据(判断注册用户名是否重复),邮箱格式检验
- 页面滚动操作onscroll事件
- 页面窗口大小改变onresize事件
- 鼠标移入移出事件onmouseover,onmouseout
作用
对于以上高频率的执行操作来说如果不进行节流控制的话,一旦请求频繁会造成页面很卡甚至死机,函数节流可以大大的减少网页请求从而提高性能
页面滚动事件不节流的效果:一次滚动执行了12次
也卖弄滚动事件节流效果:只执行了1次
代码展示
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0,minimum-scale=1.0,user-scalable=0"/> <title>Title</title> <style> * {margin: 0;padding: 0;} body{height: 2000px;} </style> </head> <body> </body> <script> window.onscroll = function () { //consoleFun();//不节流 throttle(consoleFun, 200);//节流 }; //定义节流函数 function throttle(fn,delay){ clearTimeout(fn.timer); fn.timer=setTimeout(function(){ fn(); },delay); } //定义打印函数 function consoleFun() { console.log(111); } </script> </html>