0

How do I wait 1 second before executing next function?

For example like php has sleep()

wait
  • 21
  • 1
  • 1
  • possible duplicate of [Is there a sleep function in javascript?](http://stackoverflow.com/questions/1141302/is-there-a-sleep-function-in-javascript) – lonesomeday Jul 22 '11 at 13:41
  • 3
    Exact duplicate of [What is the JavaScript version of sleep()?](http://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep) – Dan Dascalescu Oct 07 '16 at 10:30

3 Answers3

5

setTimeout(f, 1000);

Set a timeout to run a function after 1000 milliseconds

window.setTimeout[docs]

window.setTimeout[spec]

window.setTimeout[dark side]

As mentioned in the comments. JavaScript is single threaded and that thread is shared with the browser UI thread.

So by calling a blocking function like sleep. You would block the only thread. This also means that the client cannot interact with the page whilst it is blocking.

See the Event Driven Programming[wiki] article for more information

Raynos
  • 166,823
  • 56
  • 351
  • 396
  • 1
    To expand that: you don't want something like "sleep" because you don't want the browser to stop operating while you wait. Because Javascript is event-driven, you need to hand back control to the browser and tell it to wake you up after the requisite time. – Colin Fine Jul 22 '11 at 13:41
1

Even though setTimeout is supported in all major browsers, I prefer to use a javascript library because usually one is doing more js than just calling a timeout function. In YUI its:

YAHOO.lang.later(1000, this, function() {
...
});

More information here.

George P
  • 736
  • 5
  • 12
  • 2
    Why prefer to use a library for this. It seems ridiculous to include a library just for this. – Raynos Jul 22 '11 at 13:52
  • @Ryanos really!? Odds have it if the guy is using setTimeout he's probably doing more js than just calling the function to sleep for 1 second. It's good practice, plus YUI and others abstract away some complexity like interval calling. Stop being so trigger happy and go get a coffee – George P Jul 22 '11 at 13:58
  • that's a different issue. There's a difference between recommending a library for browser compliance (always good) and recommending a library to solve a very specific problem. – Raynos Jul 22 '11 at 14:05
0

You can use setTimeOut method to do so http://www.w3schools.com/js/js_timing.asp

setTimeout("alertMsg()",1000);

function alertMsg() { alert("Hello"); }

Prashant Singh
  • 3,725
  • 12
  • 62
  • 106
  • 2
    The specifics of this example are also unhelpful: It's considered bad practice to pass a string as the first argument to `setTimeout`, as it evaluates to `setTimeout(function() { eval("myFunction()"); }, 3000)`. `timeMsg` assigns the timeout handle to t, but never returns it, so there's no way to clear the timeout. It also is tightly coupled to `alertMsg` because it's using a magic string as an execution callback. – Nick Husher Jul 22 '11 at 13:50