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

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

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

exactly why I suggested using setTimeout rather than async await