这里有新鲜出炉的 Javascript 教程,程序狗速度看过来!
Javascript 是一种由 Netscape 的 LiveScript 发展而来的原型化继承的基于对象的动态类型的区分大小写的客户端脚本语言,主要目的是为了解决服务器端语言,比如 Perl,遗留的速度问题,为客户提供更流畅的浏览效果。
本文主要介绍了 JavaScript 函数节流的两种写法。具有很好的参考价值。下面跟着小编一起来看下吧
最近看了函数节流的相关内容,具体什么是节流我不讨论了,网上很多,这里总结下两个方法,我只认可其中一个。另一个貌似也能达到节流的效果但是感觉不是很正规。
方法一:
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>
- 函数节流
- </title>
- <style>
- div{ font-size:40px; color:red; text-align: center; }
- </style>
- </head>
- <body>
- <div>
- 0
- </div>
- <script>
- var a = 0;
- var oDiv = document.getElementsByTagName('div')[0];
- var throttle = function(fn, wait) {
- var startTime = new Date();
- return function() {
- var arg = arguments;
- var context = this;
- var curTime = new Date();
- // 如果达到了规定的触发时间间隔,触发 handler
- var remaing = wait - (curTime - startTime) if (remaing <= 0 || remaing > wait) { //按理说remaing足够证明已经到了时间间隔,但是为了防止客户端修改了时间所以加个条件(为什么这么加我也不懂)
- fn.apply(context, arg);
- startTime = curTime;
- }
- };
- };
- window.onmousemove = throttle(function() {
- a++;
- oDiv.innerText = a + "";
- },
- 2000);
- </script>
- </body>
- </html>
我比较认可这个方法,另外这是简洁版,还有一种可以是这样子的
- function throttle(fun, delay, time) {
- var timeout,
- startTime = new Date();
- return function() {
- var context = this,
- args = arguments,
- curTime = new Date();
- clearTimeout(timeout);
- // 如果达到了规定的触发时间间隔,触发 handler
- if (curTime - startTime >= time) {
- fun.apply(context, args);
- startTime = curTime;
- // 没达到触发间隔,重新设定定时器
- } else {
- timeout = setTimeout(function(){
- fun.apply(context, args);
- }, delay);
- }
- };
- };
就是在判断完时间间隔后再加个计时器来延迟,这个我觉得加不加都行,加了也没错跟时间判断互补,不加也能实现节流的效果。
第二类写法:
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>
- 函数节流
- </title>
- <style>
- div{ font-size:40px; color:red; text-align: center; }
- </style>
- </head>
- <body>
- <div>
- 0
- </div>
- <script>
- var a = 0;
- var oDiv = document.getElementsByTagName('div')[0];
- var throttle = function(fn, time) {
- var timer = null;
- return function() {
- var arg = arguments;
- var context = this;
- if (timer) {
- return false;
- } else {
- timer = setTimeout(function() {
- clearTimeout(timer);
- timer = null;
- fn.apply(context, arg);
- },
- time);
- }
- };
- };
- window.onmousemove = throttle(function() {
- a++;
- oDiv.innerText = a + "";
- },
- 2000);
- </script>
- </body>
- </html>
这种写法通过判断是否存在正在进行的计时器来决定是否执行函数,存在就结束运行函数,但是那个计时器仍在队列里进行实践一到还会执行,通过运行也能达到节流,也就是间隔固定的时间触发函数,但是我就是不太喜欢这种写法。可能是这种方法没第一种直接吧。
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持 phperz!
来源: http://www.phperz.com/article/17/0511/334247.html