基于特定时间延迟执行函数并忽略其他函数执行

时间:2017-10-12 01:55:35

标签: javascript settimeout setinterval

我正在摆弄setTimeOut javascript函数。我有5个不同时间延迟的函数调用。我想要的只是执行那些在每个函数之间有500ms延迟差异的函数。我创造了一个小提琴(https://jsfiddle.net/vt7sanav/)。有人建议我应该怎么做才能检查两个函数之间的延迟是500毫秒然后执行函数否则忽略函数。

示例:Packet1进来,应该立即发送(打印),等待500ms并在500ms内,忽略新的消息(函数调用)。仅打印中间延迟500毫秒的消息。

function postMessage(msg) {
  $("#msgBox").append("\n" + msg + " time:" + new Date().getSeconds() + ":" + new Date().getMilliseconds());
}

function makeRequest(msg) {
  postMessage(msg);
}

function makeRequestThrottled(msg) {
  // Packet1 comes in, should be sent straight away. wait 500ms and within 500ms,      ignore new msgs.
  postMessage(msg);
}

function sendMessage(msg, delay) {
  setTimeout(() =>
    makeRequestThrottled(msg), delay);
}

sendMessage("Packet1", 200);  //This should be printed straight away
sendMessage("Packet2", 600);   //Shouldn't be printed, difference is 400ms (Packet2 -Packet1)
sendMessage("Packet3", 1800);  // Should be printed, difference > 500ms (Packet3 -Packet2)
sendMessage("Packet4", 2400);  //Should be printed, difference > 500ms (Packet4 -Packet3)
sendMessage("Packet5", 2600);  //Shouldn't be printed, difference < 500ms (Packet4 -Packet5)

1 个答案:

答案 0 :(得分:1)

我想到的第一种做法是认为你想要做的是添加变量ignoring makeRequestThrottled()函数将用于确定当前是否忽略消息。如果没有,请发布消息,设置ignoring = true,并设置超时,在500毫秒后将ignoring设置回false

&#13;
&#13;
function postMessage(msg) {
  $("#msgBox").append("<li>" + msg + " time:" + new Date().getSeconds() + ":" + new Date().getMilliseconds());
}

function makeRequest(msg) {
  postMessage(msg);
}

var ignoring = false;

function makeRequestThrottled(msg) {
  // Packet1 comes in, should be sent straight away. wait 500ms and within 500ms,      ignore new msgs.
  if (!ignoring) {
    postMessage(msg);
    ignoring = true;
    setTimeout(() => { ignoring = false }, 500);
  }
}

function sendMessage(msg, delay) {
  setTimeout(() =>
    makeRequestThrottled(msg), delay);
}

sendMessage("Packet1", 200);  //This should be printed straight away
sendMessage("Packet2", 600);   //Shouldn't be printed, difference is 400ms (Packet2 -Packet1)
sendMessage("Packet3", 1800);  // Should be printed, difference > 500ms (Packet3 -Packet2)
sendMessage("Packet4", 2400);  //Should be printed, difference > 500ms (Packet4 -Packet3)
sendMessage("Packet5", 2600);  //Shouldn't be printed, difference < 500ms (Packet4 -Packet5)
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id="msgBox"></ul>
&#13;
&#13;
&#13;