在Node js中延迟循环



如何在每次呼叫之间延迟1秒钟,以下 makeHttpRequest 7次? - 我尝试了setTimeout和延迟,但似乎无法找到使用它们的正确方法。

var post_data = that.createIRRC("AAAAAQAAAAEAAAB1Aw==");
that.makeHttpRequest(onError, onSucces, "", post_data, false)

如果在启动下一个http请求完成之前要暂停一秒钟,则可以在完成回调中使用setTimeout()

和,由于现在看起来您要发送一系列代码,因此您可以通过要在数组中发送的代码顺序传递,这将调用每个连续代码的that.createIRRC()

function sendSequence(cntr, data, delay) {
    // create post_data for next code to send in the sequence
    let post_data = that.createIRRC(data[cntr]);
    that.makeHttpRequest(onError, function() {
        // if we haven't done this limit times yet, then set a timer and
        // run it again after one second
        if (++cntr < data.length) {
            setTimeout(function() {
                sendSequence(cntr, data, delay);
            }, delay);
        } else {
            onSuccess();
        }
    }, "", post_data,false);
}
// define the codes
// this should probably be done once at a higher level where you can define
// all the codes you might want to send so you can reference them by a meaningful
// name rather than an obscure string
let codes = {
    right: "AAAAAQAAAAEAAAAzAw==",
    down: "AAAAAQAAAAEAAABlAw==",
    select: "AAAAAQAAAAEAAABlAw==",
    options: "AAAAAgAAAJcAAAA2Aw==",
    hdmi2: "AAAAAgAAABoAAABbAw==",
    hdmi3: "AAAAAgAAABoAAABcAw=="
}
// create sequence of codes to be sent
let dataSequence = [
   codes.hdmi2, codes.options,
   codes.down, codes.down, codes.down, codes.down, codes.down, codes.down, codes.down,
   codes.right, 
   codes.down, codes.down, codes.down, codes.down,
   codes.select, codes.hdmi3
 ];
// start the process with initial cnt of 0 and 
// send the sequence of data to be sent and 
// with a one second delay between commands
sendSequence(0, dataSequence, 1000);
var times = 0;
var ivl = setInterval(function () {
    var post_data = that.createIRRC("AAAAAQAAAAEAAAB1Aw==");
    that.makeHttpRequest(onError, onSucces, "", post_data, false)
    if (++times === 7) {
        clearInterval(ivl);
    }
}, 1000);

最新更新