LoginSignup
8
9

More than 5 years have passed since last update.

Client側JavaScriptでのキューイングのSample Code

Posted at

JavaScriptはシングルタスクなので、例えば処理中の状況をブラウザ上に表示したい!といった場合に、処理を小分けにしてタイマーで順次処理するような工夫が必要になります。

お気楽極楽な感じがJavaScriptのメリットなのに、この辺りがヒジョーーにキビシイ!

その辺りを解決するために、WebWorkerが出てきましたが、こいつはサブスレッド側にプリミティブな値しか受け渡せないので、全然使い物にならないし。。。

そんなワケで、今日ボクが自分のブログで投稿した、キューイングのサンプルコードをこちらにも公開します。

Client側JavaScriptでのQueuingのSample - タイピング・ターザン

以下がサンプルコードです。

<!DOCTYPE html>
<html><head></head><body><script language="javascript">
<!--
"use strict";

/*** QUEUE ***/
var $Q = [];
var interval = 0;
function qClear() { $Q = [] }

Function.prototype.qLast = function() {
    this.args = arguments;
    $Q.push(this);
}

Function.prototype.qFirst = function() {
    this.args = arguments;
    $Q.unshift(this);
}

/*** TIMER ***/
function ontimeout() {
    try {
        if ($Q.length>0) {
            var f = $Q.shift();
            f.apply(null, f.args);
        }
    } catch (e) {
        console.log(['ontimeout:', e.description].join(''));
    }
}
window.setInterval(ontimeout, interval);

/*** Test Code ***/
function test() {
    var a = 'あいとじぇい';
    for ( var i=0; i<10; i++ ) {
        for ( var j=0; j<10; j++ ) {
            // ↓こんな感じでキュートして投げ込みたい無名ファンクションを生成
            +function(i, j) {
                console.log([a,i,j].join(':'));
            }.qLast(i, j);
        }
    }
}

window.onload = test;
-->
</script></body></html>

実行するとこんな感じでコンソール出力されるハズ。

あいとじぇい:0:0
あいとじぇい:0:1
あいとじぇい:0:2
あいとじぇい:0:3
・
・
・
あいとじぇい:1:0
あいとじぇい:1:1
あいとじぇい:1:2
あいとじぇい:1:3
・
・
・
8
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
9