关于jQuey中队列控制的两个函数 queue 和 dequeue,这两个极大方便了我们编写一些有时间差、并非立即执行完毕,却对次序要求很高的代码。
这里我再发布一个自己编写的处理队列的代码
注:这里的代码行为与jQuey的代码行为不完全
一样!
测试页面: http://shawphy.com/lab/myqueue.html
- var
myQueue
=
function
(
fnArr
){ -
//将队列放入fnArr -
this
.
fnArr
=
fnArr
||
[]
; - }
; - myQueue
.
prototype
=
{ -
fnArr
:
[]
, -
queue
:
function
(
fn
)
{ -
//如果是函数数组,则依次放入 -
if
(
fn
[
0
])
{ -
for
(
var
i
=
0
;
fn
[
i
]
;
this
.
fnArr
.
push
(
fn
[
i
++
])){} -
}
else
{ -
this
.
fnArr
.
push
(
fn
)
; -
} -
}
, -
dequeue
:
function
()
{ -
//弹出剩余的第一个函数并执行 -
(
this
.
fnArr
.
shift
()
||
function
(){})()
; -
}
, -
clear
:
function
()
{ -
this
.
fnArr
=
[]
; -
} - }
;
用法:
用new 创建一个实例:
- var
foo
=
new
myQueue
()
或者带一个函数数组:
- var
foo
=
new
myQueue
([ -
function
()
{ -
test
.
innerHTML
+=
1
; -
setTimeout
(
"
foo.dequeue()
"
,
1000
)
; -
}
, -
function
()
{ -
test
.
innerHTML
+=
2
; -
setTimeout
(
"
foo.dequeue()
"
,
1000
)
; -
} - ])
;
还可以再添加一组或者一个函数
- foo
.
queue
([ -
function
()
{ -
test
.
innerHTML
+=
3
; -
setTimeout
(
"
foo.dequeue()
"
,
1000
)
; -
}
, -
function
()
{ -
test
.
innerHTML
+=
4
; -
setTimeout
(
"
foo.dequeue()
"
,
1000
)
; -
} - ])
; - foo
.
queue
(
function
()
{ -
test
.
innerHTML
+=
5
; -
setTimeout
(
"
foo.dequeue()
"
,
1000
)
; - })
;
开始执行当前队列中的第一个函数:
- foo
.
dequeue
()
;
清空队列:
- foo
.
clear
()
;