throttle节流函数,就是一个函数调用的频率控制器;
var safe = true; function throttle() { if (safe) { lazyLoad(); safe = false; setTimeout(function() { safe = true; }, 500); } }
如下代码,safe每隔500ms才会为true,所以srollFn最快500ms执行一次。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body style="height:2000px"> <script> /*throttle节流函数,就是一个函数调用的频率控制器; 如下代码,safe每隔500ms才会为true,所以srollFn最快500ms执行一次。*/ var num = 0; function lazyLoad() { num++; console.log(num); } var safe = true; function throttle() { if (safe) { lazyLoad(); safe = false; setTimeout(function () { safe = true; }, 1000); } } window.onscroll = throttle; </script> </body> </html>