---
title: "浏览器onresize方法将被执行多次问题解决"
author: "submaze"
date: "2012-12-14T10:26:29Z"
tags: []
categories: ["Web前端"]
slug: "onresize"
draft: false
lastmod: "2012-12-14T10:29:12Z"
id: 1747574
url: "https://submaze.iteye.com/blog/1747574"
---

window对象定义其onresize事件，在拉伸缩小窗口时，其onresize方法将被执行多次，并且其具体执行的次数在不同的电脑有不同的值，相当诡异
    具体可参看这一篇文章[<window.onresize hangs IE6 and IE7>](http://remysharp.com/2008/05/15/windowonresize-hangs-ie6-and-ie7/)
    高阶函数debounce 正是为此而生的

```js

/** 
* IE下 window.onresize 有bug 可以使用debounce封装监听函数  
* see http://blog.csdn.net/fudesign2008/article/details/7035537 
* @author FuDesign2008@163.com 
* @date   2011-11-30 
* @time   下午04:02:55 
*/  
  
/** 
* 
* @param {Function} callback 回调函数 
* @param {Integer} delay   延迟时间，单位为毫秒(ms)，默认150 
* @param {Object} context  上下文，即this关键字指向的对象，默认为null 
* @return {Function} 
*/

function debounce(callback, delay, context){
    if (typeof(callback) !== "function") {
        return;
    }
    delay = delay || 150;
    context = context || null;
    var timeout;
    var runIt = function(){
            callback.apply(context);
        };
    return (function(){
	window.clearTimeout(timeout);
        timeout = window.setTimeout(runIt, delay);
    });
}
var winResizeHandler = function(event){
      console.log("window resized");
};

window.onresize= debounce(winResizeHandler, 300);


```