javascript在前6秒中每3秒设置间隔时间,然后连续5秒直到我收到答案

时间:2019-06-14 03:56:01

标签: javascript

我想在前6秒内每3秒对服务器进行一次ping响应,之后我希望将间隔时间增加到5秒,直到获得响应为止。我做了第一部分,我正在尝试解决接下来的5秒钟ping

var firstPing = 3000,
    pingStop = 6000,
    pingForever = 5000;
var ping = setInterval(function() { execute() }, firstPing);

setTimeout(function() {clearInterval(ping)}, pingStop);

setInterval(function() {execute()}, pingForever);

function execute() {
    console.log('hello: ' + new Date().getSeconds());
  // After successful response, clearInterval();

}

4 个答案:

答案 0 :(得分:2)

每1秒钟调用一次execute()并仅在递增的计数器变量为某个值时才让execute执行某些操作会更简单吗?

var ping = setInterval(function() { execute() }, 1000);

let v = 0;
function execute() {
  v++;
  if(v==3 || v==6 || (v>6 && v%5 == 1))
    console.log('hello: ' + new Date().getSeconds());
  // After successful response, clearInterval();

`

答案 1 :(得分:0)

您可以使用计数变量,您有firstPing3sec。除了清除间隔之外,您还可以使用pingForever更新firstPing。

var firstPing = 3000,
    pingStop = 6000,
    pingForever = 5000;

let count = 0;

var ping = setInterval(() => {
    execute();
    firstPing = (count === 2) ? pingForever : firstPing;
    count++;
    console.log(count, firstPing);
}, firstPing);

function execute() {
    // console.log('hello: ' + new Date().getSeconds());
}

答案 2 :(得分:0)

为简单起见,我只使用setTimeout

var found = null;

function tryRequest() {
  if (found) return;

  // send request
  // in successful response, set 'found' to 'true'

  setTimeout(tryRequest, found == null ? 3000 : 5000);
  found = false;
}

setTimeout(tryRequest, 3000);

答案 3 :(得分:0)

这里可以管理ping从3秒到5秒的过渡。

const firstPing = 3000,
      pingStop = 6000,
      pingForever = 5000;
let currentPing = 0;

let ping = setInterval(function() { execute() }, firstPing);

function execute() {
    console.log('hello: ' + new Date().getSeconds());
    // After successful response, clearInterval();
    if(++currentPing >= 2 ) {
        clearInterval(ping);
        ping = setInterval(() => execute(), pingForever);
    }
}