program story

자바 스크립트에 지연 추가

inputbox 2020. 11. 17. 08:04
반응형

자바 스크립트에 지연 추가


자바 스크립트 코드에 약 100 밀리 초의 지연을 추가해야하지만 객체 setTimeout기능 을 사용하고 window싶지 않고 바쁜 루프를 사용하고 싶지 않습니다. 누구에게 제안이 있습니까?


불행하게도, setTimeout()유일한 것입니다 신뢰할 수있는 방법 (안 유일한 방법은, 그러나 유일한 신뢰할 수있는 UI를 차단하지 않고 스크립트의 실행을 일시 정지하는 방법).

다음과 같이 작성하는 대신 실제로 사용하는 것이 그렇게 어렵지 않습니다.

var x = 1;

// Place mysterious code that blocks the thread for 100 ms.

x = x * 3 + 2;
var y = x / 2;

다음 setTimeout()과 같이 다시 작성하는 데 사용 합니다.

var x = 1;
var y = null; // To keep under proper scope

setTimeout(function() {
    x = x * 3 + 2;
    y = x / 2;
}, 100);

나는 사용 setTimeout()하는 것이 바람직한 sleep()기능 보다 더 많은 생각 포함 한다는 것을 이해 하지만 안타깝게도 나중에는 존재하지 않습니다. 이러한 기능을 구현하기위한 많은 해결 방법이 있습니다. 바쁜 루프를 사용하는 일부 :

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

다른 사용하여 XMLHttpRequest결과를 반환하기 전에 시간의 시간 동안 잠 서버 스크립트와 연결을 .

안타깝게도 이는 해결 방법이며 다른 문제 (예 : 브라우저 정지)를 일으킬 가능성이 있습니다. 권장되는 방법 인)을 고수하는 것이 좋습니다 setTimeout().


이 문제를 제대로 해결해야하는 문제가있었습니다.

Ajax를 통해 스크립트는 X (0-10) 메시지를받습니다. 내가하고 싶었던 것 : 10 초마다 DOM에 하나의 메시지를 추가합니다.

내가 끝낸 코드 :

$.each(messages, function(idx, el){
  window.setTimeout(function(){
    doSomething(el);
  },Math.floor(idx+1)*10000);
});

기본적으로 타임 아웃을 스크립트의 "타임 라인"이라고 생각하십시오.

이것이 우리가 코딩하고 싶은 것입니다.

DoSomething();
WaitAndDoNothing(5000);
DoSomethingOther();
WaitAndDoNothing(5000);
DoEvenMore();

JAVASCRIPT에이를 알려야하는 방법은 다음과 같습니다.

At Runtime 0    : DoSomething();
At Runtime 5000 : DoSomethingOther();
At Runtime 10000: DoEvenMore();

도움이 되었기를 바랍니다.


ES2017에 대해 괜찮다면 await좋습니다.

const DEF_DELAY = 1000;

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms || DEF_DELAY));
}

await sleep(100);

점을 유의 await부분은 비동기 기능에 있어야합니다 :

//IIAFE (immediately invoked async function expression)
(async()=>{
  //Do some stuff
  await sleep(100);
  //Do some more stuff
})()

Actually only setTimeout is fine for that job and normally you cannot set exact delays with non determined methods as busy loops.


This thread has a good discussion and a useful solution:

function pause( iMilliseconds )
{
    var sDialogScript = 'window.setTimeout( function () { window.close(); }, ' + iMilliseconds + ');';
    window.showModalDialog('javascript:document.writeln ("<script>' + sDialogScript + '<' + '/script>")');
}

Unfortunately it appears that this doesn't work in some versions of IE, but the thread has many other worthy proposals if that proves to be a problem for you.


Use a AJAX function which will call a php page synchronously and then in that page you can put the php usleep() function which will act as a delay.

function delay(t){

var xmlhttp;

if (window.XMLHttpRequest)

{// code for IE7+, Firefox, Chrome, Opera, Safari

xmlhttp=new XMLHttpRequest();

}

else

{// code for IE6, IE5

xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

}

xmlhttp.open("POST","http://www.hklabs.org/files/delay.php?time="+t,false);

//This will call the page named delay.php and the response will be sent to a division with ID as "response"

xmlhttp.send();

document.getElementById("response").innerHTML=xmlhttp.responseText;

}

http://www.hklabs.org/articles/put-delay-in-javascript

참고URL : https://stackoverflow.com/questions/1183872/put-a-delay-in-javascript

반응형