Michiel
Michiel

Reputation: 8083

Delay execution of JavaScript

I'm calling some JavaScript from within my PHP code, but I want the second part to hold on for 5 seconds.

I found something like setTimeOut(something, time) (JS) and .delay(time) (JQuery), but none of them seems applicable in my situation.

Here is my PHP:

$feedback = '<script>
               $(document).ready(function() {
                 noty({"text": "Yep, you did it",
                   "closeButton": true, "closeOnSelfClick": true,
                   "closeOnSelfOver": false, "modal": false
                 });
               });
             </script>

             <script>
                window.location = "http://www.mysite.be/new/index.php";        
             </script>';

It's the second part (the window.location) I want to pause for like 5 seconds. But I can't figure out how to do so. Any suggestions?

Upvotes: 3

Views: 6859

Answers (2)

Sirko
Sirko

Reputation: 74046

Replace the second part by:

<script>
  window.setTimeout( function() {
    window.location = "http://www.mysite.be/new/index.php";
    }, 5 * 1000 );
</script>

This executes the anonymous function after 5s (see MDN documentation setTimeout()).

Upvotes: 10

Juicy Scripter
Juicy Scripter

Reputation: 25918

setTimeout fits your needs:

setTimeout('window.location = "http://www.mysite.be/new/index.php";', 5000);

As not everyone is ok with eval, this may also be done with function call if eval isn't for you:

var redirect = function(){
  window.location = "http://www.mysite.be/new/index.php"
}
setTimeout(redirect, 5000)

BTW, While delay of jQuery may be used to achieve what you want it's not suited for that:

The .delay() method is best for delaying between queued jQuery effects. Because it is limited—it doesn't, for example, offer a way to cancel the delay—.delay() is not a replacement for JavaScript's native setTimeout function, which may be more appropriate for certain use cases.

Upvotes: 3

Related Questions