Simon
Simon

Reputation: 23141

setTimeout doesn't work with window.location?

i try to rich flash like effect when changing window location, but there is a small problem, i can't solve.

look at the script please

 $(document).ready(function(){

            $('a.flash').click(function(e) {
                e.preventDefault();
                $('body').fadeOut(1500);
                setTimeout("", 1500);
                window.location=this.href;
            }); 
      });

window.location=this.href must be done after 1500ms, but it doesn't happen. could you explain why? what is strange, when i try to write alert("something"); instead of window.location=this.href, it works fine. Could you explain why?

Thanks

Upvotes: 1

Views: 6083

Answers (2)

Jonathon Faust
Jonathon Faust

Reputation: 12545

setTimeout is not equivalent to a Thread.sleep(1500); in other languages. setTimeout schedules a piece of code to be run at some point in the future and does not block. Execution immediately passes the setTimeout call and continues on.

The first parameter is either a reference to a function or a string that will be evaluated.

See meder's answer for the appropriate way to use setTimeout, avoiding evaluation using an anonymous function.

Upvotes: 3

meder omuraliev
meder omuraliev

Reputation: 186562

$(document).ready(function(){

            $('a.flash').click(function(e) {
                var el = this;
                e.preventDefault();
                $('body').fadeOut(1500);
                setTimeout( function() {  location=el.href }, 1500 );
            }); 
      });

You're supposed to provide a callback function as the first param of setTimeout which is invoked after 1500 ms.

Upvotes: 7

Related Questions