How to set a variable after x seconds?

前端 未结 3 1948
清歌不尽
清歌不尽 2020-12-20 23:23

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 t

相关标签:
3条回答
  • 2020-12-20 23:50

    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 讨论(0)
  • 2020-12-20 23:58

    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.

    0 讨论(0)
  • 2020-12-21 00:01

    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

    0 讨论(0)
提交回复
热议问题