Timer的一个应用: var processor = { timeoutId: null, //method that actually performs the processing performProcessing: function(){ //actual processing code }, //method that is called to initiate processing process: function(){ //不过有没有执行,把它取消。 clearTimeout(this.timeoutId); var that = this; this.timeoutId = setTimeout(function(){ that.performProcessing(); }, 100); } }; //try to start processing processor.process(); 在这个模式中,可以保证,即使在100毫秒以内process()被调用了多次,那么performProcessing最终也只会被执行一次。 可以用以下一个精简的函数实现上面的功能:
function throttle(method, context) { clearTimeout(method.tId); method.tId= setTimeout(function(){ method.call(context); }, 100); } 在IE中,window的resize事件会调用函数多次。我们可以通过throttle函数来消除这种问题。 function resizeDiv(){ var div = document.getElementById("myDiv"); div.style.height = div.offsetWidth + "px"; } window.onresize = function(){ throttle(resizeDiv); };