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

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

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


当前回答

在Firebug(可能还有其他JavaScript控制台)中,只有在指定的睡眠时间(…)之后,点击enter后才会发生任何事情

function sleepFor(sleepDuration){
    var now = new Date().getTime();
    while(new Date().getTime() < now + sleepDuration){ /* Do nothing */ }
}

使用示例:

函数sleepFor(sleepDuration){var now=new Date().getTime();而(newDate().getTime()<now+sleepDuration){/*什么都不做*/}}函数sleepThenAt(){sleepFor(2000);console.log(“您好,JavaScript睡眠!”);}sleepThenAt()

注:仅用于调试和开发

其他回答

拥抱JavaScript的异步特性!

以下所有内容都将立即返回,但只有一个地方可以放置发生事件后要运行的代码。

我在这里概述的方法都适用于不同的用例,并根据其复杂性大致排序。

不同之处如下:

等待某些条件变为现实在调用单个回调之前,等待一组方法完成(按任何顺序)在调用回调之前,以特定顺序运行一系列具有共享状态的异步方法

Wait

如果没有任何可访问的回调来告诉您什么时候完成了执行,那么等待某个条件是否为真是非常有用的。

这是一个非常基本的实现,它假设条件在某个时刻变为真。通过一些调整,它可以扩展到更有用(例如,通过设置呼叫限制)。(我昨天才写了这篇!)

function waitFor(predicate, successCallback) {
    setTimeout(function () {
        var result = predicate();
        if (result !== undefined)
            successCallback(result);
        else
            waitFor(predicate, successCallback);
    }, 100);
}

呼叫代码:

beforeEach(function (done) {
    selectListField('A field');

    waitFor(function () {
        var availableOptions = stores.scrapeStore(optionStore);
        if (availableOptions.length !== 0)
            return availableOptions;
    }, done);
});

在这里,我调用了加载ExtJS“store”的东西,并等待该存储包含一些东西后再继续(beforeEach是Jasmine测试框架的东西)。

等待几件事完成

我还需要在加载完不同的方法后运行一个回调。你可以这样做:

createWaitRunner = function (completionCallback) {
    var callback = completionCallback;
    var completionRecord = [];
    var elements = 0;

    function maybeFinish() {
        var done = completionRecord.every(function (element) {
            return element === true
        });

        if (done)
            callback();
    }

    return {
        getNotifier: function (func) {
            func = func || function (){};

            var index = elements++;
            completionRecord[index] = false;

            return function () {
                func.applyTo(arguments);
                completionRecord[index] = true;
                maybeFinish();
            }
        }
    }
};

呼叫代码:

var waiter = createWaitRunner(done);

filterList.bindStore = waiter.getNotifier();
includeGrid.reconfigure = waiter.getNotifier(function (store) {
    includeStore = store;
});

excludeGrid.reconfigure = waiter.getNotifier(function (store) {
    excludeStore = store;
});

您可以只等待通知,也可以包装使用传递给函数的值的其他函数。调用所有方法后,将运行done。

按顺序运行异步方法

当我在一行中调用一系列异步方法时(同样在测试中),我使用了不同的方法。这有点类似于您可以在Async库中得到的东西——series也做了同样的事情,我先读了一下这个库,看看它是否符合我的要求。我认为我的测试有一个更好的API(实现起来很有趣!)。

// Provides a context for running asynchronous methods synchronously
// The context just provides a way of sharing bits of state
// Use 'run' to execute the methods.  These should be methods that take a callback and optionally the context as arguments
// Note the callback is provided first, so you have the option of just partially applying your function to the arguments you want
// instead of having to wrap even simple functions in another function

// When adding steps you can supply either just a function or a variable name and a function
// If you supply a variable name then the output of the function (which should be passed into the callback) will be written to the context
createSynchronisedRunner = function (doneFunction) {
    var context = {};

    var currentPosition = 0;
    var steps = [];

    // This is the loop. It is triggered again when each method finishes
    var runNext = function () {
        var step = steps[currentPosition];
        step.func.call(null,
                       function (output) {
                           step.outputHandler(output);
                           currentPosition++;

                           if (currentPosition === steps.length)
                               return;

                           runNext();
                       }, context);
    };

    var api = {};

    api.addStep = function (firstArg, secondArg) {
        var assignOutput;
        var func;

        // Overloads
        if (secondArg === undefined) {
            assignOutput = function () {
            };
            func = firstArg;
        }
        else {
            var propertyName = firstArg;
            assignOutput = function (output) {
                context[propertyName] = output;
            };
            func = secondArg;
        }

        steps.push({
            func: func,
            outputHandler: assignOutput
        });
    };

    api.run = function (completedAllCallback) {
        completedAllCallback = completedAllCallback || function(){};

        var lastStep = steps[steps.length - 1];
        var currentHandler = lastStep.outputHandler;
        lastStep.outputHandler = function (output) {
            currentHandler(output);
            completedAllCallback(context);
            doneFunction();
        };

        runNext();
    };

    // This is to support more flexible use where you use a done function in a different scope to initialisation
    // For example, the done of a test but create in a beforeEach
    api.setDoneCallback = function (done) {
        doneFunction = done;
    };

    return api;
};

呼叫代码:

beforeAll(function (done) {
    var runner = createSynchronisedRunner(done);
    runner.addStep('attachmentInformation', testEventService.getAttachmentCalled.partiallyApplyTo('cat eating lots of memory.jpg'));
    runner.addStep('attachment', getAttachment.partiallyApplyTo("cat eating lots of memory.jpg"));
    runner.addStep('noAttachment', getAttachment.partiallyApplyTo("somethingElse.jpg"));
    runner.run(function (context) {
        attachment = context.attachment;
        noAttachment = context.noAttachment;
    });
});

这里的PartiallyApplyTo基本上是Douglas Crockford实现Curry的重命名版本。我正在处理的很多东西都将回调作为最后的参数,这样简单的调用就可以这样完成,而不必用一个额外的函数来包装一切。

在服务器端,您可以使用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);
});

这会帮你的。

var reloadAfter = 10; //seconds
var intervalId = setTimeout(function() {
    //code you want to execute after the time waiting
}, reloadAfter * 1000); // 60000 = 60 sec = 1 min

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

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

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

sleep()的JavaScript版本是什么?

这已经在当前接受的答案中得到了回答:

await new Promise(r => setTimeout(r, 1000));

两个异步函数同时运行

最好将它放在函数sleep()中,然后等待睡眠()。要使用它,需要一些上下文:

函数sleep(ms){return new Promise(r=>setTimeout(r,ms));}(异步函数slowDemo(){console.log(“启动慢演示…”);等待睡眠(2000);console.log('lowDemo:两秒后…');})();(异步函数fastDemo(){console.log('开始快速演示…');等待睡眠(500);for(设i=1;i<6;i++){console.log('上次演示:'+(i*0.5)+'秒后…');等待睡眠(500);}})();.作为控制台包装{最大高度:100%!重要;顶部:0;}

两个异步调用依次运行–一个接一个

但假设slowDemo产生的结果是fastDemo取决于。在这种情况下,在fastDemo开始之前,slowDemo必须运行到完成:

函数sleep(ms){return new Promise(r=>setTimeout(r,ms));}(异步()=>{await(异步函数slowDemo(){console.log(“启动慢演示…”);等待睡眠(2000);console.log('slowDemo:两秒后…完成!');})();(异步函数fastDemo(){console.log('开始快速演示…');等待睡眠(500);设i=-2;对于(i=1;i<5;i++){console.log('上次演示:'+(i*0.5)+'秒后…');等待睡眠(500);}console.log('fastDemo:'+(i*0.5)+'秒后。已完成!');})();})();.作为控制台包装{最大高度:100%!重要;顶部:0;}