How can I wait In Node.js (JavaScript)? l need to pause for a period of time
Asked Answered
P

27

768

I'm developing a console script for personal needs. I need to be able to pause for an extended amount of time, but, from my research, Node.js has no way to stop as required. It’s getting hard to read users’ information after a period of time... I’ve seen some code out there, but I believe they have to have other code inside of them for them to work such as:

    setTimeout(function() {
    }, 3000);

However, I need everything after this line of code to execute after the period of time.

For example,

    // 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

I've also seen things like

    yield sleep(2000);

But Node.js doesn't recognize this.

How can I achieve this extended pause?

Pteridophyte answered 10/1, 2013 at 1:37 Comment(4)
@Christopher Allen, Maybe not relevant, but does the job: require("child_process").execSync('php -r "sleep($argv[1]);" ' + seconds);Trypanosomiasis
The node-sleep npm module might do the trick (however, I would only use it for debugging)Frech
Does this answer your question? What is the JavaScript version of sleep()?Theresa
Please don't write your own promises! Use import { setTimeout } from 'timers/promises'.Deery
C
946

Update Jan 2021: You can even do it in the Node REPL interactive using --experimental-repl-await flag

$ node --experimental-repl-await
> const delay = ms => new Promise(resolve => setTimeout(resolve, ms))
> await delay(1000) /// waiting 1 second.

A new answer to an old question. Today ( Jan 2017 June 2019) it is much easier. You can use the new async/await syntax. For example:

async function init() {
  console.log(1);
  await sleep(1000);
  console.log(2);
}

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

For using async/await out of the box without installing and plugins, you have to use node-v7 or node-v8, using the --harmony flag.

Update June 2019: By using the latest versions of NodeJS you can use it out of the box. No need to provide command line arguments. Even Google Chrome support it today.

Update May 2020: Soon you will be able to use the await syntax outside of an async function. In the top level like in this example

await sleep(1000)
function sleep(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}

The proposal is in stage 3. You can use it today by using webpack 5 (alpha),

Before that becomes available, you can just wrap the script toplevel in a self calling async function:

(async function() {
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
console.log(1)
await sleep(1000)
console.log(2)
})()

More info:

Ciera answered 31/1, 2017 at 12:5 Comment(9)
I think you forgot the await keyword in front of sleep(1000)Anisaanise
This really should be the answer, the sleep node.js package can be troublesome.Ceil
let sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); For oneliner freaks like myself :)Coumarin
let sleep = require('util').promisify(setTimeout); works on Node 7.6+ and improves readabilityOrlan
This saved my bacon today (specifically the promisify recipe @BrianHVB posted).Estheresthesia
This works perfect for me, used it as a RateLimiter for an appParamorph
Note that if you are using this inside a loop, it won't work if you're doing x.forEach. You will have to use a modern for ... of loop instead, as detailed in this answer: #37577185Guile
This is a great answer as it sums up the different ways to do it over the years. Please, consider another update at the top using setTimeout from timers/promises. See the answer from @maxim-orlov which is far below (link)Somme
If your using Sinon.useFakeTimers in your tests, make sure to not stub setTimeout (which it does by default) or you'll be wondering why this doesn't work like me >_>Doerrer
C
757

The shortest solution without any dependencies:

await new Promise(resolve => setTimeout(resolve, 5000));
Cobalt answered 6/3, 2018 at 20:47 Comment(12)
"The height of sophistication is simplicity." -- Clare Booth Luce. This is by far the best answer, IMO.Ethelda
This is obviously much more recent than the other answers, but it's the most elegant as of 2018 that gets the job done in 1 line without any other impacts to the code.Planetarium
This is a good one. You have to be using NodeJS 7.6.0 or above though. It won't work on older versions.Sifuentes
let sleep = require('util').promisify(setTimeout); is three characters longer but reusable and more readable imoOrlan
To avoid an eslint complaint, call it resolve instead of done. I.e. await new Promise(resolve => setTimeout(resolve, 5000))Squalid
shorter version (but less comprehensive): await new Promise(r => setTimeout(r, 5000));Acronym
how would I do this in a non async function?Pilate
Now I don't have to worry about my while loops eating up my CPU resource. Just throw this one liner into the cog and it slows things down and gets the job done.Conjoint
I still get this eslint complaint for this solution - eslint.org/docs/rules/no-promise-executor-returnUnclear
Nice job guys upvoting this answer. Next thing is you copy & paste it 50x into your code, what could possibly go wrong?Exhaustion
This is the best answer imo!Dairy
why can't we convert this return promise to an async/await function?Colson
S
252

Best way to do this is to break your code into multiple functions, like this:

function function1() {
    // stuff you want to happen right away
    console.log('Welcome to My Console,');
}

function function2() {
    // all the stuff you want to happen after that pause
    console.log('Blah blah blah blah extra-blah');
}

// call the first chunk of code right away
function1();

// call the rest of the code and have it execute after 3 seconds
setTimeout(function2, 3000);

It's similar to JohnnyHK's solution, but much neater and easier to extend.

Stylus answered 10/1, 2013 at 1:46 Comment(5)
@LucasSeveryn You're doing something wrong, then. This is a core design pattern.Stylus
And what do you do when the start of the function is not just one function away, but 10 files away from the code that needs to be de-asynchronized ?Merrile
@CyrilDuchon-Doris What?Arris
use @machineghost's answer for an elegant promise based solution that requires no custom code and supports await/asyncCockatoo
This is async, it means that if function1 terminates before 3 seconds, they start overlapping each other. Then you can't even return and it's almost never utilizable. The only way I found so far was using debugger;Gunrunning
M
202

This is a simple blocking technique:

var waitTill = new Date(new Date().getTime() + seconds * 1000);
while(waitTill > new Date()){}

It's blocking insofar as nothing else will happen in your script (like callbacks). But since this is a console script, maybe it is what you need!

Menado answered 1/6, 2016 at 17:51 Comment(12)
horrible or not, it does a simple wait, it blocks and it works for some testing purpose. Exactly what I was searching for.Ora
perfectly answers the question without 3rd party libs, and is simple. Yet people say "horrible" .... This is great e.g. for simulating heavy CPU load etc. Btw very similar to this phpied.com/sleep-in-javascriptFlavoprotein
Also this is the required approach if you are trying to simulate something that would slow down the event loop, thus slowing other users/connections as well. Adding delayed callbacks won't impact other users/connections.Flavoprotein
This is a spin-wait.Groundnut
This is the worst way of sleeping, it blocks the main node thread!Paresis
@Paresis that seems to be the goal.Sekyere
this is crazy, it blocks everythingAluin
This is a cpu hogger and consumes memory, better reuse the date object instead of creating a new one each time.Laconism
@codebeat It actually doesn't make any difference if you're spin-waiting. That's the spin part!Menado
This severely impacts the CPU cycleTincher
This is the only correct answer to the question. The OP asked specifically to call a wait function, return from the function, and continue. (No callbacks, no async anything, no rewriting your whole call stack to handle promises.) The only other solution that does exactly what the OP wanted is to call an external program, for example SLEEP.EXE on Windows.Creosol
This burns CPU as fast as V8 allows just to do nothingScuffle
C
165

Put the code that you want executed after the delay within the setTimeout callback:

console.log('Welcome to My Console,');
setTimeout(function() {
    console.log('Blah blah blah blah extra-blah');
}, 3000);
Celeriac answered 10/1, 2013 at 1:44 Comment(5)
This is terribly messy and generally bad practice, especially if the OP wants the rest of the program to run after that delay. See my answer.Stylus
@ElliotBonneville It's just an example to illustrate the concept. Obviously you could (should) factor the code into a function call instead instead of using inline code, just like anywhere else.Celeriac
@ChristopherKemp: Turns out Node.js has a solution for this called node-fibers. Check it out.Stylus
This is a great solution, particularly if you don't want to execute any code, you just want to mimic a "sleep" method inside a loop. Nothing wrong with this example.Slaby
this is perfect for delaying on requests coming from client, I used this approach to test my loading spinners on client sideManthei
S
122

On Node 7.6.0 or higher

Node supports waiting natively:

const sleep = (waitTimeInMs) => new Promise(resolve => setTimeout(resolve, waitTimeInMs));

then if you can use async functions:

await sleep(10000); // sleep for 10 seconds

or:

sleep(10000).then(() => {
  // This will execute 10 seconds from now
});

On older Node versions (original answer)

I wanted an asynchronous sleep that worked in Windows & Linux, without hogging my CPU with a long while loop. I tried the sleep package but it wouldn't install on my Windows box. I ended up using:

https://www.npmjs.com/package/system-sleep

To install it, type:

npm install system-sleep

In your code,

var sleep = require('system-sleep');
sleep(10*1000); // sleep for 10 seconds

Works like a charm.

Sifuentes answered 13/1, 2017 at 18:56 Comment(13)
great answer thanks - it made some impossible code possible - this is NOT a spin-waitPhotomontage
On further research this module relies on deasync which is forked from another deasync github repo. The original repo warns not to use it as it is a hack. It does work but not on all platforms so if you need a cross platform solution avoid this one.Photomontage
That's weird. We use it on both Linux & Windows successfully. What OS doesn't work?Sifuentes
looks at the issues on the system-sleep github repo and there's no guarantee this will work in the future - check out the system-sleep code to see what module it uses under the hood then look at the module that was forked from and the warning givenPhotomontage
It looks like its only dependency is here: github.com/jakwuh/deasync-promise. I don't see anything wrong with that project, nor any warnings. Do I have the wrong project?Sifuentes
dependency of system-sleep is deasync-promise whose dependency is deasync - and deasync is a fork of github.com/vkurchatkin/deasync - you cant sleep the main thread without hacking it in node - which is what deasync doesPhotomontage
yes, i've never experienced probs with it and its great for dev - under the hood I believe it relies on C or C++ which is widely available but I guess on some machines its not and thats when it fails which is why it causes issues - if it fails system sleep falls back to a spin wait which will freeze code executionPhotomontage
This package doesn't work on Mac OS, and is therefore not cross compatible, and therefore not workable. See github.com/jochemstoel/nodejs-system-sleep/issues/4Alveolate
@Nuzzolilo That's weird. We have one developer on Mac OS and he's never mentioned anything wrong. I suspect it's a specific Mac OS version. I also updated this answer since sleep is basically built into newer versions of NodeJS.Sifuentes
Interestingly enough, this solution produces odd results when stdin's raw mode is set to true. My code is hosted here: helperbot3.ngrok.io/public/code0.js This is node.js 12.18.2, by the way.Ubangi
@Ubangi If you are using node 12.18.2 you should be using the On Node 7.6.0 or higher section.Sifuentes
This should be higher. Brilliant answerForetooth
works like charm. perfect!Glochidium
E
70

Simple and elegant sleep function using modern Javascript

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

No dependencies, no callback hell; that's it :-)


Considering the example given in the question, this is how we would sleep between two console logs:

async function main() {
    console.log("Foo");
    await sleep(2000);
    console.log("Bar");
}

main();

The "drawback" is that your main function now has to be async as well. But, considering you are already writing modern Javascript code, you are probably (or at least should be!) using async/await all over your code, so this is really not an issue. All modern browsers today support it.

Giving a little insight into the sleep function for those that are not used to async/await and fat arrow operators, this is the verbose way of writing it:

function sleep(millis) {
    return new Promise(function (resolve, reject) {
        setTimeout(function () { resolve(); }, millis);
    });
}

Using the fat arrow operator, though, makes it even smaller (and more elegant).

Encrimson answered 13/10, 2017 at 0:14 Comment(3)
You can also write the sleep function without the async and leaving everything else the same. It is probably clearer with the async though.Optician
Good catch, @KevinPeña. Matter of fact, I think I prefer it without async. Edited my answer with your suggestion. I don't think it makes the code clearer; for that, I'd resort to JSDoc instead.Encrimson
I like to have the following one-liner in my scripts: const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));Etruscan
B
70

From Node.js 15 and up you can use the Timers Promises API. You don't have to promisify setTimeout or rely on a 3rd party library anymore.

import { setTimeout } from 'node:timers/promises';

await setTimeout(1000);
Bertiebertila answered 11/3, 2022 at 17:39 Comment(2)
This is the correct solution - please don't write your own promises.Deery
Absolutely the correct solution.Moth
B
53

You can use this www.npmjs.com/package/sleep

var sleep = require('sleep');
sleep.sleep(10); // sleep for ten seconds
Bilabial answered 22/4, 2016 at 17:40 Comment(3)
It works fine on MacOS, but it encounter errors on CentOS due to node_gyp errors. It seems not portable.Covington
perhaps problem caused not by OS, but by node buildBilabial
This is a newer feature, and so will require a newer version of Node.Dormancy
D
44

If you want to "code golf" you can make a shorter version of some of the other answers here:

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

But really the ideal answer in my opinion is to use Node's util library and its promisify function, which is designed for exactly this sort of thing (making promise-based versions of previously existing non-promise-based stuff):

const util = require('util');
const sleep = util.promisify(setTimeout);

In either case you can then pause simply by using await to call your sleep function:

await sleep(1000); // sleep for 1s/1000ms

EDIT: As noted in the comments, you can even reduce that to one line:

const sleep = require('util').promisify(setTimeout);

Or, if you don't even want to bother making a sleep function:

await require('util').promisify(setTimeout)(1000);
Dormancy answered 24/10, 2017 at 0:38 Comment(4)
Actually, using util.promisify, it is not possible to call sleep without also providing a callback. nodejs.org/api/…Unceremonious
You're missing the await. It sort of creates a callback, pauses things, and then restarts the code when that callback returns. The callback returns with a value, but we don't care about it in this case, so there's nothing to the left of await.Dormancy
write it in one line to wine the code golf ;) const sleep = require('util').promisify(setTimeout);Apostatize
@Fabian, and if you need it only once: await require('util').promisify(setTimeout)(1000);Vial
P
35

This question is quite old, but recently V8 has added Generators which can accomplish what the OP requested. Generators are generally easiest to use for async interactions with the assistance of a library such as suspend or gen-run.

Here's an example using suspend:

suspend(function* () {
    console.log('Welcome to My Console,');
    yield setTimeout(suspend.resume(), 10000); // 10 seconds pass..
    console.log('Blah blah blah blah extra-blah');
})();

Related reading (by way of shameless self promotion): What's the Big Deal with Generators?.

Prodigy answered 21/8, 2013 at 14:11 Comment(5)
Good answer - But should read yield setTimeout(suspend.resume(), 10000);Chapa
Thanks, @edhubbell. This answer was based on a very old version of suspend, but you're right regarding the latest. I'll update the answer.Prodigy
what version of node is this for?Photomontage
@Photomontage I can't recall exactly when they were un-flagged, but they've been around since v0.12 behind the --harmony flag, and according to node.green, they're at least available without any flags since v4.8.4: node.green/#ES2015-functions-generators-basic-functionality. Please note, however, that the newer async/await syntax provides a better solution to this now, with no need for extra libraries like suspend. See this answer for an example: https://mcmap.net/q/36254/-how-can-i-wait-in-node-js-javascript-l-need-to-pause-for-a-period-of-time. Async functions are available (without flags) since v7.10.Prodigy
This is very complicated as of 2021.Theresa
L
30

Try using promise, it works for me in NodeJS

one liner

await new Promise(resolve => setTimeout(resolve, 5000));

or have it as a function in NodeJS to re-use

const sleep = async (milliseconds) => {
    await new Promise(resolve => setTimeout(resolve, milliseconds));
}

use the function like

await sleep(5000)
Logographic answered 10/6, 2021 at 8:15 Comment(0)
C
23

On Linux/nodejs this works for me:

const spawnSync = require('child_process').spawnSync;

var sleep = spawnSync('sleep', [1.5]);

It is blocking, but it is not a busy wait loop.

The time you specify is in seconds but can be a fraction. I don't know if other OS's have a similar command.

Cantrell answered 18/11, 2016 at 18:50 Comment(1)
sleep is pretty much omnipresent and a utiltiy arround since early UNIX days en.wikipedia.org/wiki/Sleep_%28Unix%29. Only "not rare" os it would maybe not exist is windows (however there you could attempt child_process.spawnSync('timeout', ['/T', '10'])Cesium
S
19

Node 16 has a new way to do it easily

import { setTimeout } from 'timers/promises'

console.log('before')
await setTimeout(3000)
console.log('after')
Slink answered 7/9, 2022 at 19:27 Comment(1)
This is literally the same as Maxim Orlov's answer.Atharvaveda
P
14

I've recently created simpler abstraction called wait.for to call async functions in sync mode (based on node-fibers). There is also a version based on upcoming ES6 Generators.

https://github.com/luciotato/waitfor

Using wait.for, you can call any standard nodejs async function, as if it were a sync function, without blocking node's event loop.

You can code sequentially when you need it, which is, (I'm guessing) perfect to simplify your scripts for personal use.

using wait.for your code will be:

require('waitfor')

..in a fiber..
//start-of-code
console.log('Welcome to My Console,');
wait.miliseconds(10*1000); //defined in waitfor/paralell-tests.js - DOES NOT BLOCK
console.log('Blah blah blah blah extra-blah');
//endcode. 

Also any async function can be called in Sync mode. Check the examples.

Phylys answered 6/9, 2013 at 13:58 Comment(4)
TypeError: Object #<Object> has no method 'miliseconds'Frampton
the comment says: "//defined in waitfor/paralell-tests.js" grab it from that file.Phylys
after I got it from wait.for/paralell-tests.js I encountered a another errors related to undefined properties etc. So I needed to copy them too. Why don't you organize the code in a way that this will not be required?Rahmann
Wait.for and other fiber solutions have opened up a whole new world to me! I'd up vote this a million times if I could. Although most of the nodejs community oppose fibers, I think they're a fantastic addition and definitely have their place when it comes to callback hell.Provence
D
10

Since, javascript engine (v8) runs code based on sequence of events in event-queue, There is no strict that javascript exactly trigger the execution at after specified time. That is, when you set some seconds to execute the code later, triggering code is purely base on sequence in event queue. So triggering execution of code may take more than specified time.

So Node.js follows,

process.nextTick()

to run the code later instead setTimeout(). For example,

process.nextTick(function(){
    console.log("This will be printed later");
});
Dagger answered 10/1, 2013 at 11:22 Comment(0)
G
2

With ES6 supporting Promises, we can use them without any third-party aid.

const sleep = (seconds) => {
    return new Promise((resolve, reject) => {
        setTimeout(resolve, (seconds * 1000));
    });
};

// We are not using `reject` anywhere, but it is good to
// stick to standard signature.

Then use it like this:

const waitThenDo(howLong, doWhat) => {
    return sleep(howLong).then(doWhat);
};

Note that the doWhat function becomes the resolve callback within the new Promise(...).

Also note that this is ASYNCHRONOUS sleep. It does not block the event loop. If you need blocking sleep, use this library which realizes blocking sleep with the help of C++ bindings. (Although the need for a blocking sleep in Node like async environments is rare.)

https://github.com/erikdubbelboer/node-sleep

Geocentric answered 18/5, 2017 at 0:34 Comment(0)
O
1

In order to "wait" in javascript using promises are the way to go as the top answers show.

So how can it be used?

Here's a simple example of a 5-second sub-process queuing up parameters for a 4-second main process in a non-blocking manner.

const wait = (seconds) => 
    new Promise(resolve => 
        setTimeout(() => 
            resolve(true), seconds * 1000))

const process = async (items, prepTask, mainTask) => {
    const queue = [];
    let done = false;

    items.forEach((item, i) => {
        prepTask(item).then(() => {
            queue.push(item);
            if (i == items.length -1) {
                done = true;
            }
        })
    })

    while (!done || queue.length) {
        if (queue.length) {
            const workload = queue.shift();
            await mainTask(workload)
        } else {
            console.log('waiting for subtask to queue')
            await wait(1);
        }
    }
}

// Usage Example

const ids = [1,2,3,4,5,6,7,8,9,10];

const prepTask = async (id) => {
    await wait(id * 5)
    return id * 5;
}

const mainTask = async (workload) => {
    console.log('excuting workload: ', workload);
    const result = await wait(4);
    return { workload, result }
}

process(ids, prepTask, mainTask)
    .then(() => console.log('done'))
Onto answered 31/10, 2021 at 21:40 Comment(0)
A
0
let co = require('co');
const sleep = ms => new Promise(res => setTimeout(res, ms));

co(function*() {
    console.log('Welcome to My Console,');
    yield sleep(3000);
    console.log('Blah blah blah blah extra-blah');
});

This code above is the side effect of the solving Javascript's asynchronous callback hell problem. This is also the reason I think that makes Javascript a useful language in the backend. Actually this is the most exciting improvement introduced to modern Javascript in my opinion. To fully understand how it works, how generator works needs to be fully understood. The function keyword followed by a * is called a generator function in modern Javascript. The npm package co provided a runner function to run a generator.

Essentially generator function provided a way to pause the execution of a function with yield keyword, at the same time, yield in a generator function made it possible to exchange information between inside the generator and the caller. This provided a mechanism for the caller to extract data from a promise from an asynchronous call and to pass the resolved data back to the generator. Effectively, it makes an asynchronous call synchronous.

Assignee answered 8/3, 2017 at 9:58 Comment(2)
While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.Gabby
Thanks @DonaldDuck. The code in my answer is probably the most exciting part of improvement in Javascript. I'm so amazed that some super smart people think about this way to solve the callback hell problem.Assignee
D
0

simple we are going to wait for 5 seconds for some event to happen (that would be indicated by done variable set to true somewhere else in the code) or when timeout expires that we will check every 100ms

    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;
        }
    })();
Dewey answered 22/3, 2017 at 14:54 Comment(0)
E
0

For some people, the accepted answer is not working, I found this other answer and it is working for me: How can I pass a parameter to a setTimeout() callback?

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

'hello' is the parameter being passed, you can pass all the parameters after the timeout time. Thanks to @Fabio Phms for the answer.

Enroot answered 13/4, 2017 at 18:49 Comment(0)
A
0

This is a moment.js flavored module based on the dirty blocking approach suggested by @atlex2. Use this only for testing.

const moment = require('moment');

let sleep = (secondsToSleep = 1) => {
    let sleepUntill = moment().add(secondsToSleep, 'seconds');
    while(moment().isBefore(sleepUntill)) { /* block the process */ }
}

module.exports = sleep;
Aardvark answered 8/11, 2017 at 14:11 Comment(0)
F
0
function doThen(conditional,then,timer) {
    var timer = timer || 1;
    var interval = setInterval(function(){
        if(conditional()) {
            clearInterval(interval);
            then();
        }
    }, timer);
}

Example usage:

var counter = 1;
doThen(
    function() {
        counter++;
        return counter == 1000;
    },
    function() {
        console.log("Counter hit 1000"); // 1000 repeats later
    }
)
Florettaflorette answered 24/6, 2020 at 16:26 Comment(0)
V
-1

If you just need to suspend for testing purpose you current thread execution try this:

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
Vent answered 29/11, 2016 at 9:19 Comment(0)
Z
-2

The other answers are great but I thought I'd take a different tact.

If all you are really looking for is to slow down a specific file in linux:

 rm slowfile; mkfifo slowfile; perl -e 'select STDOUT; $| = 1; while(<>) {print $_; sleep(1) if (($ii++ % 5) == 0); }' myfile > slowfile  &

node myprog slowfile

This will sleep 1 sec every five lines. The node program will go as slow as the writer. If it is doing other things they will continue at normal speed.

The mkfifo creates a first-in-first-out pipe. It's what makes this work. The perl line will write as fast as you want. The $|=1 says don't buffer the output.

Zebapda answered 13/3, 2017 at 21:11 Comment(0)
E
-3

I put together, after having read the answers in this question, a simple function which can also do a callback, if you need that:

function waitFor(ms, cb) {
  var waitTill = new Date(new Date().getTime() + ms);
  while(waitTill > new Date()){};
  if (cb) {
    cb()
  } else {
   return true
  }
}
Exhibitive answered 6/11, 2016 at 8:8 Comment(0)
M
-4

For more info on

yield sleep(2000); 

you should check Redux-Saga. But it is specific to your choice of Redux as your model framework (although strictly not necessary).

Madlin answered 9/9, 2016 at 9:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.