0

Wait script?

Language: JavaScript What is the line to use when you want it to wait for a second? I thought wait(1) But apparently it doesn’t work

22nd May 2021, 9:04 PM
Kiriixer
Kiriixer - avatar
5 odpowiedzi
+ 2
well javascript doesn't have any global wait function . There is a window object though . If you loop over it you will know the methods or attributes it makes available to use . You can use window.setTimeout method . setTimeout(function name, time) For example: setTimeout(test, 1000) ; function test(){ } The above will wait for 1 second and then execute test function . Also setTimeout works asynchronously , i.e. javascript will still execute other pieces of code for that 1 second outside setTimeout .
22nd May 2021, 9:29 PM
Abhay
Abhay - avatar
+ 1
Javascript seems a bit different on that compared to other languages. According to this thread I found on stackoverflow: https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep#39914235 you would need to write your own sleep function to pause the code for an amount of time function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } and use it as follow: sleep(1000) I hope this helps :)
22nd May 2021, 9:21 PM
Apollo-Roboto
Apollo-Roboto - avatar
+ 1
you cannot "wait" before continuing the script execution... but you could "timeout", or even "interval" a callback function (wich will be executed after a certain delay): setTimeout(() => { console.log("about 2 secondes ellapsed"); }, 2000); similary, there's a setInterval() function... check the documentation to know more about both: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Timeouts_and_intervals
22nd May 2021, 9:24 PM
visph
visph - avatar
+ 1
Apollo-Roboto I guess that OP expected waiting and then executing following lines of script... but your solution let next lines of script be executed without waiting ^^ even if you could block script execution by doing: await sleep(1000); that's not the correct way to do in web context javascript (all page will freeze during 1 second)... the only valuable way is to defer a function execution with setTimeout ;)
22nd May 2021, 9:38 PM
visph
visph - avatar
0
Javascript does’nt support that feature even though some functions like setTimeout seems that they can do that , but what is really doing that behind the scence is your browser engine which is written in C++ , so actually C++ is doing that for you
23rd May 2021, 5:07 AM
Nima