zoukankan      html  css  js  c++  java
  • javascript 函数节流 throttle 解决函数被频繁调用、浏览器卡顿的问题

    * 使用setTimeout

    index.html

    <html>
    <head>
    	<meta charset="UTF-8">
    	<title>throttle</title>
    </head>
    <body>
    	<h2>函数节流 解决函数被频繁调用、浏览器卡顿的问题</h2>
    	<script src="js/throttle.js"></script>
    </body>
    </html>
    

      

    js/throttle.js

    // 函数节流 解决函数被频繁调用、浏览器卡顿的问题
    var throttle = function(fn, interval) {
    	var __self = fn,       // 保存需要被延迟执行的函数引用
    		timer,             // 定时器
    		firstTime = true;  // 是否第1次被调用
    	return function() {
    		var args = arguments, __me = this;
    
    		// 如果第1次被调用, 不需要延迟执行
    		if (firstTime) {
    			__self.apply(__me, args);
    			return firstTime = false;
    		}
    		// 如果定时器还在, 说明前一次延迟执行还没有完成
    		if (timer) {
    			return false;
    		}
    		// 延迟一段时间执行
    		timer = setTimeout(function() {
    			clearTimeout(timer);
    			timer = null;
    			__self.apply(__me, args);
    		}, interval || 500);
    	}
    }
    
    var dom = document.createElement("h1");
    dom.innerHTML = 0;
    document.body.appendChild(dom);
    
    window.onresize = throttle(function() {
    	var n = parseInt(dom.innerHTML);
    	dom.innerHTML = ++n;
    }, 500);
    

      

    Run:

    php -S 0.0.0.0:9000

    调整浏览器窗口大小

  • 相关阅读:
    Qt的.pro文件
    AI_八数码
    安装 MINGW GCC 4.4.0
    VC中应用Excel
    八数码问题_启发搜索
    【收集】【收藏】【转帖】game development resouce
    QT小记之在VS2005中使用QT
    [转文]VS2008 安装 Boost 1.43.0
    搬家到博客园了
    转 暴雪总裁总结游戏十条经验
  • 原文地址:https://www.cnblogs.com/mingzhanghui/p/9407694.html
Copyright © 2011-2022 走看看