JS で多くの機能を実現できることは誰もが知っていますが、この記事では、JS の非同期関数キュー機能の実装方法と関連する操作テクニックを共有します。
シナリオ:
ライブブロードキャストを行う場合、ユーザーがマウントを持っている場合は、数秒間入場の特殊効果を表示する必要があります。同時に、どのように表示すればよいでしょうか?このとき、setTimeout 関数を考えることになります。はい、そのアイデアは良いのですが、非同期関数キューを実装するにはどうすればよいでしょうか。コードに直接移動します:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | var Queue = function () {
this.list = [];
};
Queue.prototype = {
constructor: Queue,
queue: function (fn) {
this.list.push(fn)
return this;
},
wait: function (ms) {
this.list.push(ms)
return this;
},
dequeue: function () {
var self = this,
list = self.list;
self.isdequeue = true;
var el = list.shift() || function () {};
if (typeof el == "number" ) {
setTimeout( function () {
self.dequeue();
}, el);
} else if (typeof el == "function" ) {
el.call(this)
if (list.length) {
self.dequeue();
} else {
self.isdequeue = false;
}
}
}
};
|
ログイン後にコピー
例:
a と b がほぼ同時に入ってくる場合、a と b が完全にキューから出ていないときに
c が入った場合、a、b、 c はすべてキューから削除されています。もう一度入ってください。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | var q = new Queue();
function a() {
console.log( "a执行了" , new Date ());
}
function b() {
console.log( "b执行了" , new Date ());
}
function c() {
console.log( "c执行了" , new Date ());
}
function d() {
console.log( "d执行了" , new Date ());
}
q.wait(2000);
q.queue(a);
q.wait(2000);
q.queue(b);
q.dequeue();
setTimeout( function (){
q.wait(2000);
q.queue(c);
},3000);
setTimeout( function (){
q.wait(2000);
q.queue(d);
q.dequeue();
},8000);
|
ログイン後にコピー
ここでは、デキューをいつ呼び出すかを決定する必要があります。 (c がキューに入ったときにデキューする必要がないのに、d が入ったときにデキューが必要になるのはなぜですか?)
しかし、一般に、ユーザーがいつサイトに入ったかはわかりません。通常、キューに入った後は退出できるはずです。 . Queue ですが、キューが空のときにユーザーが入ってくると、以前の dequeue の再帰呼び出しが実行されるため、入ってきたときに再度実行する必要があります。
デキュー操作。
つまり、コードは次のようになります:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | var q = new Queue();
function a() {
console.log( "a执行了" , new Date ());
}
function b() {
console.log( "b执行了" , new Date ());
}
function c() {
console.log( "c执行了" , new Date ());
}
function d() {
console.log( "d执行了" , new Date ());
}
q.wait(2000);
q.queue(a);
if (!q.isdequeue) {
q.dequeue();
}
q.wait(2000);
q.queue(b);
if (!q.isdequeue) {
q.dequeue();
}
setTimeout( function () {
q.wait(2000);
q.queue(c);
if (!q.isdequeue) {
q.dequeue();
}
}, 3000);
setTimeout( function () {
q.wait(2000);
q.queue(d);
if (!q.isdequeue) {
q.dequeue();
}
}, 8000);
|
ログイン後にコピー
このようにして、キューに入るたびにキューから出るかどうかを判断し、問題は解決します。
上記の内容は、JSの非同期関数キュー機能の実装方法と関連する操作テクニックです。
関連する推奨事項:
非同期関数の使用方法?非同期関数インスタンスの使い方まとめ
JavaScript非同期関数の戻り値の取得方法を詳しく解説
JavaScript非同期関数の戻り値の取得方法
以上がJS非同期関数キュー機能とその操作スキルの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。