views:

192

answers:

3

Im basically trying to accomplish the following. I want it so 5 seconds after the page loads, it'll set the variable to true.

Once true, it'll proceed to give the alert "true".. for now.

If someone tries to click the button before 5 seconds, it'll give the alert false.

Here's what i managed to type up. Isn't exactly working. Thanks :)

http://pastebin.com/m799d3957

+5  A: 

Try this:

setTimeout(function() { window.link = true; }, 5000);

This will set the global variable "link" to true after 5 seconds, which will satisfy your if statement.

Edit This may be a bit complicated if you're a beginner, but a better way to accomplish this is to use function-scope rather than global scope.

In your case, declare the timer function like this:

var timer = (function () {
 var link = false;
 setTimeout(function() { link = true; }, 5000);

 return function() {
  alert(link);
 };
}());

This way, the anonymous function returns another function which becomes timer(), but this way timer has access to its "private" link variable. For more information, check out Mozilla's article on JavaScript variable scope

Matt
Marius, while I appreciate you making the effort to edit, the curly brace you removed is a necessary part of the code (it closes the initial function block)Rolled back.
Matt
+2  A: 

You've got the right idea, but you have a minor issue with variable scope. To reduce headaches, it's really best to get away from using the string eval option on setTimeout (which is shown in tutorials all around the web, I know) and use an anonymous function:

var link;
function loading(){
    setTimeout(function(){ 
        link = true; 
    }, 5000);
}

This way, you'll know exactly where link is declared and the scope is crystal clear.

brianreavis
A: 

it worked. thanks a ton

Ricky
Please don't forget to mark your preferred answer as accepted, so the credit can be given. Thanks.
Matt