How do I write a blocking synchronous method in Javascript?

会有一股神秘感。 提交于 2019-12-30 04:43:08

问题


I'm trying to mock out a method which takes a long time for testing purposes but can't find a good way to do this in Javascript. Any good approaches besides writing a very long for loop?


回答1:


How about a loop that checks time?

function sleep(milliSeconds){
    var startTime = new Date().getTime();                    // get the current time
    while (new Date().getTime() < startTime + milliSeconds); // hog cpu until time's up
}



回答2:


You could make a synchronous AJAX call to a server which defers the response by a certain amount of time as requested by your script. Note however that this method won't work in Firefox as it doesn't support synchronous AJAX calls.

Just use this simple function on the client side:

function sleep(microseconds) {
    var request = new XMLHttpRequest;
    request.open("GET", "/sleep.php?time=" + milliseconds);
    request.send();
}

The code for sleep.php on the server side:

usleep(intval($_GET("sleep")));

Now you can create blocking synchronous functions in JavaScript (with the exception of Firefox) as follows:

alert("Hello");
sleep(1000000); // sleep for 1 second
alert("World");



回答3:


If you can use the newer await/await syntax:

function sleep (time) {
  return new Promise((resolve) => setTimeout(resolve, time));
}

async function example() {
    await sleep(4000);
    return 1;
}

console.log(await example());


来源:https://stackoverflow.com/questions/10527503/how-do-i-write-a-blocking-synchronous-method-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!