Skip to content
time.sleep() function in JavaScript?
Profile icon

Like how Python has a time.sleep function to delay code execution, does JavaScript have a similar time function that delays code the same way? Can this be applied to a script page in HTML?

You are viewing a single comment. View All
Profile icon


already mentioned, the fundamental way you create a delay is by using setTimeout and setInterval

i will add it is unlikely that you will freeze your website (as you would if you put while(true) {} at the top of your script block) whether or not you use callbacks, promises, or async / await

if it is a simple delay, then using setTimeout is perfectly fine. if you find yourself using a lot of delays, you may find that the callback-based setTimeout can get unwieldy quite quickly

using callbacks, for example, if i have 5 delays of 1 second each, the code will look like this, with a lot of nesting

s(1000, function() { console.log('s step 1') s(1000, function() { console.log('s step 2') s(1000, function() { console.log('s step 3') s(1000, function() { console.log('s step 4') s(1000, function() { console.log('s step 5') }) }) }) }) })

using promises, this has the same behaviour as the above code

p(1000) .then(function() { console.log('p setp 1') return p(1000) }) .then(function() { console.log('p step 2') return p(1000) }) .then(function() { console.log('p step 3') return p(1000) }) .then(function() { console.log('p step 4') return p(1000) }) .then(function() { console.log('p step 5') })

using async / await, this has the same behaviour as the above code

!(async function() { await p(1000) console.log('p step 1 await') await p(1000) console.log('p step 2 await') await p(1000) console.log('p step 3 await') await p(1000) console.log('p step 4 await') await p(1000) console.log('p step 5 await') })()

you don't really have to understand how each piece of code works to see which one looks the simplest to write. either the middle or the last one, probably looks nice to you

if you want to see a super simple example of these three different methods (without them being repeated 5 times), i have a repl here you can take a look at. some code is commented out, which of course you can uncomment if you want to see the behaviour of it

for some reason a 'false' is printed in the repl i linked. not sure why that is, but you can ignore that. also, the p function you see me use is essentially thesetTimeout function, wrapped in a promise. since you appear to be new to javascript, i would not worry about that right now.

Profile icon

markdown 2nd line