-1

I know the time.sleep functiom from python. I just want to waot 3 seconds without making a callback. If i had to implemebt a callback i also had to hanfle global vars and more callbacks. I would like to have a function:

function getdata() {
console.log("hello");
Sleep(3000);
console.log("stackoverflow!");
return "my data";}

Please don't give me a solution for my specific example... i would also need sleep in while functions and other things. I searched a lot but i only found (in exanple setTimeout) functions with callback.

famemaker
  • 111
  • 7
  • Please. Any search answers that question. – Denys Séguret Apr 27 '16 at 17:19
  • JS is single-threaded, there is no sleep functionality. – Dan Macak Apr 27 '16 at 17:21
  • You won't get far with JavaScript if you don't become familiar with callbacks and asynchronous code flow. *"I searched a lot but i only found (in exanple setTimeout) functions with callback."* Maybe that is an indication that this is the only real solution to that problem? – Felix Kling Apr 27 '16 at 17:21
  • If you can use `async` and `await` you can implement `getData` "inline" but you'd still need `then` and a callback to get at the final returned result. https://babeljs.io/repl/#?evaluate=true&presets=es2015%2Creact%2Cstage-2&code=function%20sleep(ms)%20%7B%0A%20%20return%20new%20Promise(resolve%20%3D%3E%20setTimeout(resolve%2C%20ms))%3B%0A%7D%0A%0Aasync%20function%20getData()%20%7B%0A%20%20console.log(%22hello%22)%3B%0A%20%20await%20sleep(3000)%3B%0A%20%20console.log(%22stackoverflow!%22)%3B%0A%20%20return%20%22my%20data%22%3B%0A%7D%0A%0AgetData().then(result%20%3D%3E%20console.log(result))%0A – Thomas Upton Apr 27 '16 at 17:27
  • Ok. Thank you for your answers. BUT!: I have only basic knowledge in JS and i really searched. I found many StackOverflow Q/A sites which all said: you COULD use setTimeout... So please downvote me. I spent one hour of googling ;-) – famemaker Apr 27 '16 at 17:32
  • Why wouldn't while (starttime + wait_seconds - currentTime > 0) {/*wait/*} work? – famemaker Apr 27 '16 at 17:36
  • It "works" in so far that it prevents any other code to run. It basically freezes the browsers. And any delay > 100ms is pretty noticeable by users. How would you feel if you couldn't scroll the page for 3 seconds (and you wouldn't know why)? If you are trying to use this to "wait" for an Ajax response, it won't work because the code to handle the response cannot execute. – Felix Kling Apr 27 '16 at 18:59

1 Answers1

1

It doesn't exist. Javascript isn't designed this way. You need to use a callback and setTimeout. Sorry!

Darth Egregious
  • 18,184
  • 3
  • 32
  • 54