1

NodeJS 環境で、1 秒間に 30 回実行されるループを作成しようとしています (固定変数に基づく)。私は、NodeJSの I/O キューに準拠するために利用できるので、NodeJS に関しては、それは適切な方法ではないsetIntervalと言われました。次のコードを使用してみました ( ):setTimeoutprocess.nextTicksetImmediatesetImmediate

var Physics = {
    lastTime: (new Date().getTime()),
    upsCounter: 0,
    ups: 0,

    init: function() {
        Physics.loop();
    },

    loop: function() {
        var currentTime = (new Date().getTime());
        Physics.upsCounter += 1;

        if((currentTime - Physics.lastTime) >= 1000) {
            Physics.ups = Physics.upsCounter;
            Physics.upsCounter = 0;
            Physics.lastTime = currentTime;

            console.log('UPS: ' + Physics.getUPS());
        }

        setImmediate(Physics.loop);
    },

    getUPS: function() {
        return this.ups;
    }

};

私の問題は、Updates Per Second (UPS) が必要な 30 ではなく 400,000 を超えていることです。これをこの数に制限する方法、または別のループ構造があるかどうか疑問に思っていました。ありがとう

4

2 に答える 2

0

先に進んでsetIntervalorsetTimeoutメソッドを使用する必要がありますが、そのタイマーがプログラムの主な実行でない限り、それらがそうでなければ終了するプロセスを保持しないように、それらを参照解除してください。

参照:ノード タイマー API ドキュメント

javascript var t = setInterval(myMethod, 100); t.unref(); //the timer t will not execute if the rest of the program is ready to exit.

于 2014-05-16T21:32:55.677 に答える