有没有比下面的pausecomp函数(取自此处)更好的方法来设计JavaScript中的睡眠?

function pausecomp(millis)
{
    var date = new Date();
    var curDate = null;
    do { curDate = new Date(); }
    while(curDate-date < millis);
}

这不是JavaScript中的Sleep的重复-动作之间的延迟;我希望在函数的中间有一个真正的睡眠,而不是在代码执行之前有一段延迟。


当前回答

在服务器端,您可以使用deasync sleep()方法,该方法在C中本地实现,因此它可以有效地实现等待效果,而不会阻塞事件循环或将CPU置于100%负载。

例子:

#!/usr/bin/env node

// Requires `npm install --save deasync`
var sleep = require("deasync").sleep;

sleep(5000);

console.log ("Hello World!!");

但是,如果您需要一个纯JavaScript函数(例如,通过浏览器在客户端运行它),我很抱歉地说,我认为您的pausecomp()函数是实现它的唯一方法,而且,除此之外:

这不仅会暂停函数,还会暂停整个事件循环。因此,将不会参加其他活动。它使您的CPU处于100%负载。

因此,如果您需要它作为浏览器脚本,并且不希望出现这些可怕的效果,我必须说,您应该以某种方式重新思考您的功能:

a) 。您可以在超时时调用它(或调用do_the_rest()函数)。如果您不期望从函数中得到任何结果,则使用更简单的方法。

b) 。或者,如果你需要等待结果,那么你应该使用promise(当然,也可以使用回调地狱;-))。

无预期结果示例:

function myFunc() {

    console.log ("Do some things");

    setTimeout(function doTheRest(){
        console.log ("Do more things...");
    }, 5000);

    // Returns undefined.
};

myFunc();

返回promise的示例(注意它会改变函数的用法):

function myFunc(someString) {

    return new Promise(function(resolve, reject) {

        var result = [someString];
        result.push("Do some things");

        setTimeout(function(){
            result.push("Do more things...");
            resolve(result.join("\n"));
        }, 5000);
    });
};


// But notice that this approach affect to the function usage...
// (It returns a promise, not actual data):
myFunc("Hello!!").then(function(data){
    console.log(data);
}).catch(function(err){
    console.error(err);
});

其他回答

在服务器端,您可以使用deasync sleep()方法,该方法在C中本地实现,因此它可以有效地实现等待效果,而不会阻塞事件循环或将CPU置于100%负载。

例子:

#!/usr/bin/env node

// Requires `npm install --save deasync`
var sleep = require("deasync").sleep;

sleep(5000);

console.log ("Hello World!!");

但是,如果您需要一个纯JavaScript函数(例如,通过浏览器在客户端运行它),我很抱歉地说,我认为您的pausecomp()函数是实现它的唯一方法,而且,除此之外:

这不仅会暂停函数,还会暂停整个事件循环。因此,将不会参加其他活动。它使您的CPU处于100%负载。

因此,如果您需要它作为浏览器脚本,并且不希望出现这些可怕的效果,我必须说,您应该以某种方式重新思考您的功能:

a) 。您可以在超时时调用它(或调用do_the_rest()函数)。如果您不期望从函数中得到任何结果,则使用更简单的方法。

b) 。或者,如果你需要等待结果,那么你应该使用promise(当然,也可以使用回调地狱;-))。

无预期结果示例:

function myFunc() {

    console.log ("Do some things");

    setTimeout(function doTheRest(){
        console.log ("Do more things...");
    }, 5000);

    // Returns undefined.
};

myFunc();

返回promise的示例(注意它会改变函数的用法):

function myFunc(someString) {

    return new Promise(function(resolve, reject) {

        var result = [someString];
        result.push("Do some things");

        setTimeout(function(){
            result.push("Do more things...");
            resolve(result.join("\n"));
        }, 5000);
    });
};


// But notice that this approach affect to the function usage...
// (It returns a promise, not actual data):
myFunc("Hello!!").then(function(data){
    console.log(data);
}).catch(function(err){
    console.error(err);
});
require('deasync').sleep(100);

现在还可以使用本机模块util来提供常规同步函数。

const { promisify } = require('util')
const sleep = promisify(setTimeout)

module.exports = () => {
  await someAsyncFunction()
  await sleep(2000)
  console.log('2 seconds later...')
}

在sleep方法中,可以返回任何可执行的对象。不一定是新的承诺。

例子:

constsleep=(t)=>({then:(r)=>setTimeout(r,t)})常量someMethod=async()=>{console.log(“hi”);等待睡眠(5000)console.log(“再见”);}someMethod()

一种非常简单的睡眠方式,它将与运行JavaScript的任何东西兼容。。。这段代码已经过500个条目的测试,CPU和内存的使用情况在我的web浏览器上仍然不可见。

这里有一个函数,它等待节点变为可见。。。

此函数创建一个新的上下文函数(){}以避免递归。我们在这个新上下文中放置了与调用者代码相同的代码。我们使用函数Timeout在几秒钟后调用我们的函数。

var get_hyper = function(node, maxcount, only_relation) {
    if (node.offsetParent === null) {
        // node is hidden
        setTimeout(function () { get_hyper(node, maxcount, only_relation)}, 
                   1000);
        return;
    };

    // Enter the code here that waits for that node becoming visible
    // before getting executed.

};