admin管理员组

文章数量:1296304

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

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

Share Improve this question asked Jun 13, 2010 at 17:42 SimonSimon 23.1k36 gold badges93 silver badges123 bronze badges 1
  • why it works when i wrote alert()??? in that case it "sleeps" 1500ms, and after it makes alert. why? – Simon Commented Jun 13, 2010 at 17:51
Add a ment  | 

2 Answers 2

Reset to default 7
$(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.

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.

本文标签: javascriptsetTimeout doesn39t work with windowlocationStack Overflow