3

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?

2 Answers 2

10

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()).

Sign up to request clarification or add additional context in comments.

3 Comments

Why is your answer better (or worse) then the one from Juicy? :-)
@Michiel Just read in the comments to his questions and decide for yourself. I personally do not put strings as parameters to eval()-like functions. But as is pointed out in the comments, it shouldn't make much difference here.
@Michiel, it's nicer because of mine uses technique that may very easily lead to mess in code and harden understanding of what code does. Practically it's leads to the same result.
3

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.

4 Comments

Even in that case, the (unnecessary) performance drawback remains.
@Sirko, I'm not arguing about usage of eval in generic, but you will not gain any performance by replacing eval with function call in that case
Thanks @JuicyScripter for your answer (and the complementary documentation)!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.