How can I wait In Node.js (JavaScript)? l need to pause for a period of time
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),
More info:
- Harmony Flag in Nodejs: https://nodejs.org/en/docs/es6/
- All NodeJS Version for download: https://nodejs.org/en/download/releases/
Pause script until user presses enter in Node.JS
You can simply take input from stdin
Sample function :
function waitForKey(keyCode) {
return new Promise(resolve => {
process.stdin.on('data',function (chunk) {
if (chunk[0] === keyCode) {
resolve();
process.stdin.pause();
}
});
});
}
Now if you want to wait for enter key :
await waitForKey(10);
What is the JavaScript version of sleep()?
2017 — 2021 update
Since 2009 when this question was asked, JavaScript has evolved significantly. All other answers are now obsolete or overly complicated. Here is the current best practice:
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
Or as a one-liner:
await new Promise(r => setTimeout(r, 2000));
As a function:
const sleep = ms => new Promise(r => setTimeout(r, ms));
or in Typescript:
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
use it as:
await sleep(<duration>);
Demo:
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function demo() {
for (let i = 0; i < 5; i++) {
console.log(`Waiting ${i} seconds...`);
await sleep(i * 1000);
}
console.log('Done');
}
demo();
How do you wait for a return from a function before moving on in node
It seems like your BitX library doesn't have a promise interface but is callback-based, so you need to promisify it:
const { promisify } = require('util')
async function get_ticker(){
let BitX = require('../lib/BitX')
while(true){
let bitx = new BitX(key, secret)
let tick = await promisify(bitx.getTicker).call(bitx)
get_info(tick)
console.log(i)
i = i + 1
}
}
It would be more performant to create the client only once though:
const { promisify } = require('util')
const BitX = require('../lib/BitX')
const bitx = new BitX(key, secret)
const getBitxTicker = promisify(bitx.getTicker).bind(bitx)
async function get_ticker(){
while(true){
const tick = await getBitxTicker()
get_info(tick)
console.log(i)
i = i + 1
}
}
(Note that I used bind
instead of call
now for binding the bitx
instance, because we don't immediately call it now.)
How to wait for a period of time after a function run
Just put your code inside an anonymous function passed to setTimeout.
e.g.
functionToRunFirst();
setTimeout(function() {
// rest of code here
}, 2000);
Wait for user input every time and continue in the loop. Using node js
You could use readline.question
with async-await
:
const readline = require('readline');
function readInput() {
const interface = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
return new Promise(resolve => interface.question("Please provide next input: ", answer => {
interface.close();
resolve(answer);
}))
}
(async () => {
const array = [1, 2];
const array2 = [4, 5];
for (const a of array) {
for (const b of array2) {
const data = await readInput();
// Do something with your data...
console.log(data, a, b);
}
}
})();
Related Topics
Force Download an Image Using JavaScript
Why Does "True" == True Show False in JavaScript
Will Const and Let Make the Iife Pattern Unnecessary
How to Pause Setinterval() Functions
How to Format a Utc Date as a 'Yyyy-Mm-Dd Hh:Mm:Ss' String Using Nodejs
How to Access the Http Request Header Fields via JavaScript
Send a File as Multipart Through Xmlhttprequest
How to Execute Array of Promises in Sequential Order
Change Second Select List Based on First Select List Value in Rails
Rails 4 Client Side Validation
Has Anyone Else Run into Problems Styling Twitter Typeahead's Searchbar
How to See Ping Pong in Web Socket in iOS
Resolve Circular References from JSON Object
Using Socket.Io in Express 4 and Express-Generator's /Bin/Www