【随笔】一个简单的JavaScript异步处理事件队列

当我们需要连续执行几个函数,而这几个函数会一直对页面元素进行操作时,很可能页面会出现短暂的卡,然后,一下子爆炸性的出现所有信息。

一般我们会用setTimeout(fn,0);这种来执行,其实js的setTimeout,特别是IE6的,响应时间最快也要17毫秒左右,所以,设置成0,意义不大。

而且,这种做法,存在不连续,不连贯性。所以,自己写了个简单的。

 

 1 /**
 2  * @author floyd
 3  * @name 异步处理事件队列
 4  * @example var qe = new QueneEnginer();qe.add(fn,context,arrParam);qe.start();
 5  */
 6 
 7 var QueneEnginer = function(){
 8 
 9     this.Quene = [];
10 }
11 QueneEnginer.prototype = {
12     processTime : 20,
13     /**
14      * 添加事件到队列中
15      * @param {function} fn 函数对象
16      * @param {object} context 上下文对象 可为空
17      * @param {array} arrParam 参数数组 可为空
18      */
19     add : function(fn,context,arrParam){
20 
21         this.Quene.push(
22             {
23                 fn : fn,
24                 context : context,
25                 param : arrParam
26             }
27         );
28     },
29     start : function(){
30         var that = this;
31         setTimeout(function(){that.process();},that.processTime);
32     },
33     process : function(){
34         
35         var quene = this.Quene.shift();
36         
37         if(!quene)return ;
38 
39         quene.fn.apply(quene.context,quene.param);
40         
41         quene = null;
42         
43         this.start();
44     }
45 }

 

posted @ 2011-03-24 14:46  Floyd  阅读(2439)  评论(8编辑  收藏  举报