0% found this document useful (0 votes)
25 views

How to Wait 1 Second in JavaScript - Mastering JS

esperar 1 segundo

Uploaded by

cleiton.lopes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

How to Wait 1 Second in JavaScript - Mastering JS

esperar 1 segundo

Uploaded by

cleiton.lopes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

12/12/2024, 10:45 How to Wait 1 Second in JavaScript - Mastering JS

Mastering JS ☰
Tutorials / Fundamentals /

How to Wait 1 Second in JavaScript


Aug 27, 2021

To delay a function execution in JavaScript by 1 second, wrap a promise execution


inside a function and wrap the Promise's resolve() in a setTimeout() as shown
below. setTimeout() accepts time in milliseconds, so setTimeout(fn, 1000) tells
JavaScript to call fn after 1 second.

function delay(time) {
return new Promise(resolve => setTimeout(resolve, time));
}

delay(1000).then(() => console.log('ran after 1 second1 passed'));

You could also wrap the delay call in an async function to use async await instead of
then() :

function delay(time) {
return new Promise(resolve => setTimeout(resolve, time));
}

async function test() {


console.log('start timer');
await delay(1000);
console.log('after 1 second');
}

test();

You may also skip the extra delay() function and just inline the Promise constructor
call as shown below.

async function test() {


console.log('start timer');
await new Promise(resolve => setTimeout(resolve, 1000));
console.log('after 1 second');
}

test();

https://masteringjs.io/tutorials/fundamentals/wait-1-second-then 1/3
12/12/2024, 10:45 How to Wait 1 Second in JavaScript - Mastering JS

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!
Star 150

More Fundamentals Tutorials


The `setTimeout()` Function in JavaScript
JavaScript Array flatMap()
How to Get Distinct Values in a JavaScript Array
Check if a Date is Valid in JavaScript
Encode base64 in JavaScript
Check if URL Contains a String
JavaScript Add Month to Date

Tutorials eBooks Resources

Fundamentals Mastering About


Node Mongoose Partnerships
Vue
Webpack
Axios
Mongoose
Express
Lodash
npm
Miami Beach, FL ESLint
Sinon
Copyright © MeanIT Software,
Inc. Subscribe to our Newsletter ›
Subscribe

https://masteringjs.io/tutorials/fundamentals/wait-1-second-then 2/3
12/12/2024, 10:45 How to Wait 1 Second in JavaScript - Mastering JS

https://masteringjs.io/tutorials/fundamentals/wait-1-second-then 3/3

You might also like