2017-10-12 12 views
0

javascript 함수 setTimeOut을 둘러보고 있습니다. 다른 시간 지연과 5 함수 호출했습니다. 내가 원하는 것은 각 기능들간에 500ms의 지연 차이를 갖는 기능들만을 실행하는 것이다. 나는 바이올린 (https://jsfiddle.net/vt7sanav/)을 만들었습니다. 누군가가 두 함수 사이의 지연을 검사하기 위해해야 ​​할 것을 제안 할 수 있습니까? 그렇다면 함수를 무시하고 다른 함수를 실행하십시오.특정 시간 지연을 기준으로 함수를 실행하고 다른 함수 실행을 무시하십시오.

예 : Packet1이 들어오고, 곧바로 보내야합니다 (인쇄). 500ms를 기다렸다가 500ms 이내에 새 메시지 (함수 호출)를 무시하십시오. 그 사이에 500ms의 지연이있는 메시지 만 인쇄하십시오.

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

자바 스크립트가 본질적으로 asychronous입니다. 당신은'약속'을 찾고 있습니다. –

+0

makeRequestThrottled 호출에서 setTimeout을 사용하여 수행 할 수 있다고 생각하지만 확실하지 않은 이유는 – zubairm

답변

1

난 당신이 makeRequestThrottled() 기능은 메시지가 현재 무시되고 있는지 여부를 확인하는 데 사용하는 변수, ignoring을 추가하는 것이었다하려고 노력하고 생각 일을하는 마음에 온 첫 번째 방법. 그렇지 않은 경우, 메시지를 게시, ignoring = true을 설정은 500ms 후 다시 false-ignoring을 설정하는 시간 제한 설정 :

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)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<ul id="msgBox"></ul>

+0

입니다. 감사 – zubairm