Main javascript question: after 5 seconds set the variable to true

Im basically trying to do the following. I want this to happen 5 seconds after the page loads, it will set the variable to true.

As soon as true, it will continue to issue a warning of "true" .. for now.

If someone tries to click the button for up to 5 seconds, this will give a false warning.

Here is what I managed to print. Doesn't quite work. Thanks:)

http://pastebin.com/m799d3957

+4
source share
2 answers

You have the right idea, but you have a small problem with a variable scope. To reduce headaches, it is best to avoid using the eval string options on setTimeout (as shown in tutorials all over the Internet, I know) and use an anonymous function:

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

This way you will know exactly where the link declared, and the area is crystal clear.

+6
source

Try the following:

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

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

Edit This may be a little tricky if you're a beginner, but the best way to achieve this is to use a functional area rather than a global area.

In your case, declare the timer function as follows:

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

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

+9
source

All Articles