猿问

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

我想在前 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();


}


慕田峪7331174
浏览 168回答 3
3回答

HUH函数

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

尚方宝剑之说

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

慕容3067478

我只是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);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答