如何在JavaScript/jquery中实现非阻塞睡眠?

2wnc66cl  于 2023-10-17  发布在  jQuery
关注(0)|答案(3)|浏览(109)

如何在JavaScript/jquery中实现非阻塞睡眠?

kx7yvsdv

kx7yvsdv1#

冒着从评论者那里窃取答案的风险,使用setTimeout()。举例来说:

var aWhile = 5000; // 5 seconds
var doSomethingAfterAWhile = function() {
  // do something
}
setTimeout( doSomethingAfterAWhile, aWhile );
wqlqzqxt

wqlqzqxt2#

自ECMAScript 2017以来,您可以从async/await中受益:
https://jsfiddle.net/2tavp61e/

function delay (miliseconds) {
    return new Promise((resolve) => {
        window.setTimeout(() => {
            resolve();
        }, miliseconds);
    });
}

(async function () {
    console.log('A');
    await delay(2000);
    console.log('B');
})();

console.log('C');

“A”首先出现在控制台中,“C”紧随其后-这证明延迟是非阻塞的,最后两秒钟后出现“B”。

oxcyiej7

oxcyiej73#

Node内部,不使用new Promise()显式

const util = require("util");
      const sleep = util.promisify(setTimeout);
      await sleep(5000); // waiting 5 seconds
      // now send response
      await res.status(401).send("incorrect username or password");
      return;

相关问题