如何在Node.js(JavaScript)中等待?我需要暂停一段时间。

740

我正在为个人需求开发控制台脚本。我需要能够暂停一段较长的时间,但是从我的研究来看,Node.js没有相应的停止方式。在一段时间后,读取用户信息变得困难... 我看到了一些代码,但我认为它们必须包含其他代码才能正常工作,例如:

    setTimeout(function() {
    }, 3000);

然而,我需要这行代码后的所有内容在一段时间后执行。

例如,

    // start of code
    console.log('Welcome to my console,');

    some-wait-code-here-for-ten-seconds...

    console.log('Blah blah blah blah extra-blah');
    // end of code

我也看到过类似的事情

    yield sleep(2000);

但是Node.js无法识别这个。

我该如何实现这个延长的暂停时间呢?


4
@Christopher Allen,也许不是很相关,但可以胜任任务: require("child_process").execSync('php -r "sleep($argv[1]);" ' + seconds); 意思是通过Node.js的child_process模块执行一条命令,即在PHP中运行一个代码段来使程序等待指定的秒数。 - Haitham Sweilem
node-sleep npm 模块可能会有用(但是,我只会在调试时使用它)。 - julian soro
1
这回答解决了你的问题吗?JavaScript 中类似于 sleep() 函数的方法是什么? - Dan Dascalescu
2
请不要编写自己的 Promises!使用 import { setTimeout } from 'timers/promises' - Nick Grealy
27个回答

-1

对于一些人来说,被接受的答案并不能解决问题。我发现了另一个可行的答案,在这里分享出来:如何向setTimeout()回调函数传递参数?

var hello = "Hello World";
setTimeout(alert, 1000, hello); 

'hello'是传递的参数,您可以在超时时间之后传递所有参数。感谢@Fabio Phms的答案。


-1

简单来说,我们将等待5秒钟以便某个事件发生(这将由代码中的done变量设置为true表示),或者当超时时间到达时,我们将每100毫秒检查一次。

    var timeout=5000; //will wait for 5 seconds or untildone
    var scope = this; //bind this to scope variable
    (function() {
        if (timeout<=0 || scope.done) //timeout expired or done
        {
            scope.callback();//some function to call after we are done
        }
        else
        {
            setTimeout(arguments.callee,100) //call itself again until done
            timeout -= 100;
        }
    })();

-1
function doThen(conditional,then,timer) {
    var timer = timer || 1;
    var interval = setInterval(function(){
        if(conditional()) {
            clearInterval(interval);
            then();
        }
    }, timer);
}

使用示例:

var counter = 1;
doThen(
    function() {
        counter++;
        return counter == 1000;
    },
    function() {
        console.log("Counter hit 1000"); // 1000 repeats later
    }
)

-2

如果你只是为了测试目的而需要暂停当前线程执行,请尝试以下方法:

function longExecFunc(callback, count) {

    for (var j = 0; j < count; j++) {
        for (var i = 1; i < (1 << 30); i++) {
            var q = Math.sqrt(1 << 30);
        }
    }
    callback();
}
longExecFunc(() => { console.log('done!')}, 5); //5, 6 ... whatever. Higher -- longer

-3
其他答案都很好,但我想采取不同的方法。
如果你只是想在Linux中减慢特定文件的速度:
 rm slowfile; mkfifo slowfile; perl -e 'select STDOUT; $| = 1; while(<>) {print $_; sleep(1) if (($ii++ % 5) == 0); }' myfile > slowfile  &

node myprog slowfile

这将使程序每五行休眠1秒。Node程序将与写入者一样慢。如果它正在执行其他任务,它们将以正常速度继续。

mkfifo创建了一个先进先出的管道。这是使其工作的关键。 perl行将按您想要的速度快速写入。$|=1表示不缓冲输出。


-4

我在阅读了这个问题的答案之后,编写了一个简单的函数,如果需要的话还可以进行回调:

function waitFor(ms, cb) {
  var waitTill = new Date(new Date().getTime() + ms);
  while(waitTill > new Date()){};
  if (cb) {
    cb()
  } else {
   return true
  }
}

-5

更多信息请参考

yield sleep(2000); 

你应该查看Redux-Saga。但它是针对你选择Redux作为模型框架的(尽管不是必需的)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接