Skip to content
← Back to Community
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?

Profile icon
Profile icon
Profile icon

as @MrEconomical 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

@eankeen markdown 2nd line

Profile icon

Sorry if this is an terribly, revoltingly, extremely late answer, but check out this link. It will answer your question:

Profile icon

javascript has setTimeout() and setInterval()

setTimeout() is basically time.sleep in that you can delay the execution of some code, and setInterval() just executes code every time in an interval

however, unlike python, javascript is ASYNCHRONOUS so setTimeout() SCHEDULES the execution of some code and meanwhile other code runs

I highly recommend you to embrace the asyncrhonous nature of javascript

but if you want to get around this problem there is something called async await in which you can wait for some piece of code to execute

so something like this

async function a() { await b() console.log("done") } function b() { return new Promise(function(resolve, reject) { setTimeout(function() { resolve() }, 1000) }) } a()

as you can see the "done" statement is printed after 1 second of waiting for b
read more about it here:

however I STILL HIGHLY RECOMMEND TO GET USED TO ASYNC JAVASCRIPT BECAUSE IT LETS YOU DO SOME VERY COOL THINGS (because it is for front-end user interaction your site won't freeze for 1 sec while you are waiting to execute some code, rather you can schedule it with setTimeout())

just get used to async code execution its really cool once you learn how to use it

Profile icon

@MrEconomical nice, but i would add that using async await hardly lets you 'get around this problem'. slight technicalities aside, it simply allows you sort of rewrite the problem using a different syntax, especially relative to the promise-based api way of doing things

once top level await is more supported by browsers, then using async / await would be more prone to cause a detriment to script / site performance (more for beginners) since you would not be chunking your code meant to be asynchronous in function blocks. on the contrary, it would wait for the promise to resolve before the rest of the script executes (and before we get a change to register ui event listeners, assuming they show up 'under' the 'await' keywords in the same execution context)
ex. (within a script)

let myData = await fetch('') document.querySelector('button').addEventListener(() => console.log('interactive button clicked'))
Profile icon

@eankeen exactly why I suggested using setTimeout rather than async await