- ;
- function Queue() {
- // 数据缓存对象
- var cache = {};
- var queueList = {
- // type默认是fx,是动画队列
- queue: function(type, data) {
- var args = arguments;
- //没有参数直接返回
- if (!args.length) {
- return;
- }
- var q = null;
- // 只有一个参数并且是个函数
- if (args.length == 1 && typeof type === 'function') {
- data = type;
- type = 'fx';
- }
- q = cache[type] || [];
- // 添加缓存
- if (data instanceof Array) {
- q = data;
- } else {
- q.push(data)
- }
- cache[type] = q;
- //如果是动画队列并且没有开始的动画,执行第一个动画函数
- if (type == 'fx' && q.toString().indexOf('inprogress') === -1) {
- queueList.dequeue()
- }
- return q;
- },
- dequeue: function(type) {
- var fn, queue;
- type = type || 'fx';
- queue = cache[type];
- if (queue.length == 0) {
- return;
- }
- fn = queue.shift();
- if (fn === 'inprogress') {
- fn = queue.shift();
- }
- if (fn) {
- if (type === 'fx') {
- queue.unshift('inprogress');
- }
- fn.call(null,
- function() {
- queueList.dequeue(type);
- })
- }
- },
- // 延迟使用setTimeout来实现
- delay: function(type, timeout) {
- if (!type) {
- return;
- }
- if (arguments.length == 1) {
- timeout = type;
- type = 'fx';
- }
- if (typeof timeout == 'number') {
- var q = cache[type];
- if (!q) {
- q = cache[type] = [_delay];
- } else {
- q.push(_delay)
- }
- }
- function _delay() {
- setTimeout(queueList.dequeue, timeout);
- }
- return this;
- },
- get: function(type) {
- type = type || 'fx';
- return cache[type];
- }
- }
- return queueList;
- }
来源: http://www.cnblogs.com/xujiazheng/p/6413104.html