循环使用Node JS延迟

时间:2017-05-30 20:16:55

标签: javascript node.js

如何循环下面makeHttpRequest 7次,每次通话之间延迟1秒? - 我已尝试setTimeout并延迟但似乎无法找到使用它们的正确方法。

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

2 个答案:

答案 0 :(得分:0)

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);

答案 1 :(得分:0)

如果您想在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);