views:

55

answers:

2

I am trying to redirect the user to a different page after 1 second via javascript:

setTimout("document.location.href='new_page.html'", 1000);

however, in Internet Explorer, this happens immediately, not 1 second later. Any thoughts?

A: 

Wrap it in a function.

setTimeout( function() { location.href = 'new_page.html'; }, 1000 );

Note that, if you are always doing this on page load, you should really use the meta refresh tag instead.

 <meta http-equiv="refresh" content="1;url=new_page.html">
tvanfosson
What he has *should* work (except it should be `window.location`), you're allowed to use code in a string. It's not a *good* idea, but you can.
T.J. Crowder
@T.J. Crowder - I took the OP at his word (since I'm using Mac/Safari right now) and simply provided a more correct implementation that I knew would work. Even if the code in the question works, I think it should still be wrapped into a function instead of forcing the interpreter to eval the string.
tvanfosson
@tvanfosson: `setTimeout` accepting a string has nothing to do with a specific browser, it's been that way from the beginning.
T.J. Crowder
+3  A: 

What you've quoted should work, except for a couple of minor errors:

  1. You're missing the "e" in setTimeout

  2. You're using document.location; it should be window.location.

Just tested it on IE8 and it waited as expected. Are you doing this from within some event that would make the page reload anyway, like a form's submit event? If so, you'll need to cancel the form submission to avoid that superceding your setTimeout code. How you do that will depend on how you're hooking the event (e.g., if you're using a DOM0 onsubmit="..." handler, use return false;; if you're using something more modern, you want event.preventDefault(); if you're using jQuery, Prototype, or some other library, check their docs for the right way to prevent the default action of the event).

Now, although it works the way you did it, it's typically better to do this with a function rather than code within a string, e.g.:

setTimeout(function() {
    window.location.href = 'new_page.html';
}, 1000);

But either way should work.

T.J. Crowder