开发者

How to set a variable after x seconds?

I'm 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 seco开发者_如何学JAVAnds, it'll give the alert false.


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.


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


Simple one-liner timeout:

setTimeout(() => alert("Time is up!"), 1000);

You can obviously execute any code within:

let seconds = 5;
let timer = setInterval(() => console.log(`${seconds--} seconds left`), 1000);

setTimeout(() => {
  clearInterval(timer);
  console.log('
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜