tags:

views:

73

answers:

1
+1  Q: 

setTimout help

I have a small piece of javascript that I would like to use but need a delay before it's activated.

function sglClick(url) {
    window.setTimeout('location.href="http://'"+url",1500);
}

This is not working and I'm really stuck here. Wish I knew a bit more javascript. Can someone please help?

Thanks


Here is what I now have

function send(){

}

function sglClick(url) {
//    window.location.href="http://"+url;
    setTimeout(function send() { location.href = "http://" + url; },1500);
}
+6  A: 

try this

function sglClick(url) {
    setTimeout(function() { location.href = "http://" + url; },1500);
}

This is using an anonymous function to house your code. It should take approx 1.5 seconds to fire. I say approx because JavaScript is single threaded, and other function calls/etc can actually make the interval fire at a slightly different time (but 9/10 this is a non-issue)

It is also assuming you're sending things like this to the function

sglClick('www.google.com');

As your code is prefixing the argument with http://

I've always used this function as just simply setTimeout(), not as a method of the window object.

alex
Hey Alex, thanks! This other function... What should go in it?
Which function are you referring to?
alex
Well, I figured I would would make a new function and call it "send". Basically, I want to wait about half a second before sending the user to the url
When this function is invoked, it will automatically wait 1.5 seconds and send the user to the computed address. If you'd like, you can rename this function to send().
alex
@alex: By the way, in JavaScript, "window.something" is the same as "something". So, "setTimeout" refers to the same function/method that "window.setTimeout" refers to.
Steve Harrison
Alex.. Thank you so much! I just wish I understood *why* it is working. The new function you had me create is empty. So how is it working?
@Tim: The new function isn't "empty". It contains the code 'location.href = "http://" + url;'. However, it has no name, which is why it is called an "anonymous function".
Steve Harrison
Whoops! In its commenting system, StackOverflow seems to turn anything that has http[colon]// into a link, so the code snippet in my previous comment didn't come out completely right...
Steve Harrison
Its weird because I deleted that function and it still works. In other words.. Alex wrote function() and I changed it to function send() then actually created a function called send. After I tested it with send() having an empty code block, I deleted it. It still works though. Why?
I'm sorry, if my last post was not clear, I can post my code up top.