2017-05-30 79 views
-3

如何在每次调用之间以1秒的延迟循环播放7次以下的makeHttpRequest? - 我试过setTimeout并延迟,但似乎无法解决使用它们的正确方法。使用节点JS中的延迟进行循环播放

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

向我们展示'setTimeout'的尝试,请 – Bergi

回答

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

请注意,这里'onError'和'onSuccess'将被多次调用 – arboreal84

+0

@ arboreal84 - 不,“onError'只会被调用一次。循环在调用onError之后停止 - 这是故意设计的。 'onSuccess'会被多次调用,因为这似乎是OP所需要的,否则OP将无法从每次调用中获取响应。 – jfriend00

+0

我在哪里放置createIRRC行? - 我一直在尝试这两个代码,并通过@ arboreal84,我无法得到任何工作:(我试图发送代码序列(选项/向下x 6 /右/下/选择/ HDMI3 ),以选择一个特定的功能(没有谨慎的代码可用)。如果我使用多个“that.makeHttpRequest(onError,onSucces,”,“post_data,false);”行有效*有时*,其他人会感到困惑。 – Jason

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

@Jason - 请注意,此答案每秒都会发起一个新请求。它不会在前一个请求完成后等待1秒(所以它取决于是否正是您想要的 - 如果响应变慢,您可能一次发出多个请求,响应甚至可能失序尽管这不太可能)。如果出现错误,它也不会中止,它只是继续前进。 – jfriend00

+0

我已经提供了答案。 – jfriend00