Question

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

Was it helpful?

Solution

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top