为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕田峪7331174 2021-06-28 08:55:41
我想在前 6 秒内每 3 秒 ping 一个服务器以进行响应,之后我想将间隔时间增加到 5 秒,直到我得到响应。我做了第一部分,我正在尝试解决接下来的 5 秒 pingvar 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();}
查看完整描述

3 回答

?
HUH函数

TA贡献1836条经验 获得超4个赞

这是管理 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);

    }

}


查看完整回答
反对 回复 2021-07-01
?
尚方宝剑之说

TA贡献1788条经验 获得超4个赞

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


查看完整回答
反对 回复 2021-07-01
?
慕容3067478

TA贡献1773条经验 获得超3个赞

我只是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);


查看完整回答
反对 回复 2021-07-01
  • 3 回答
  • 0 关注
  • 167 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信