简体   繁体   English

全局变量创建为 setInterval function 无法从函数内部访问

[英]Global variable created as setInterval function not accessible from within functions

I am setting an interval in the global scope so it can be cleared and restarted within functions.我在全局 scope 中设置了一个间隔,以便可以在函数内清除和重新启动它。 However, when I call it from within a function, it seems to be undefined.但是,当我从 function 中调用它时,它似乎是未定义的。 My understanding (and I've just done a ton of reading) is that Javascript variables defined outside of functions (var this = '' OR var this;) are global and accessible from anywhere else in the code.我的理解(我刚刚阅读了大量内容)是在函数之外定义的 Javascript 变量(var this = '' OR var this;)是全局的,并且可以从代码中的其他任何地方访问。 Every time I check my (allegedly) global variable from within a function, it is inaccessible.每次我从 function 中检查我的(据称)全局变量时,它都无法访问。

As far as defining my global variable, I have tried a few options and none have worked.至于定义我的全局变量,我尝试了一些选项,但都没有奏效。 I have tried setting the variable but not giving it a value:我试过设置变量但没有给它一个值:

var mainTimeout;

I have tried setting it AND giving it an initial value:我试过设置它并给它一个初始值:

var mainTimeout='x';

I have tried setting it as the actual time interval that it will eventually be:我尝试将其设置为最终的实际时间间隔:

var mainTimeout = setInterval(function(){setTimeClckState('default');}, 15000);

Regardless of which option I choose, I try calling it later from within a function like this:无论我选择哪个选项,我都会尝试稍后从 function 中调用它,如下所示:

$(".timeClckControls input[type=button]").click(function(){
    if(mainTimeout){clearInterval(mainTimeout)}else{console.log('no timeout var set');};
});

Without fail, I always get console logged "no timeout var set".毫无疑问,我总是让控制台记录“没有设置超时变量”。 So it is never being recognized from within the function, even though I defined my variable with global scope.所以它永远不会在 function 中被识别,即使我用全局 scope 定义了我的变量。 The result of this is that my time interval just stacks and it constantly triggers after the function is triggered a few times.这样做的结果是我的时间间隔只是堆叠,并且在 function 被触发几次后不断触发。 Please help, I am out of ideas!请帮忙,我没有想法!

Full Code:完整代码:

var mainTimeout = setInterval(function(){setTimeClckState('default');}, 15000);

$(".timeClckControls input[type=button]").click(function(){
    if(!($(this).val()=='IN')&&!($(this).val()=='OUT')){
        // IF CLEAR BUTTON, SET TIME CLOCK TO DEFAULT
        if($(this).val()=="CL"){
            setTimeClckState('default');
        // IF BUTTON IS 4TH CHARACTER
        }else if($('#empIDTxt').val().length==3){
            $('#empIDTxt').val($('#empIDTxt').val()+$(this).val());
            $('.timeClckControls .btn-primary').prop('disabled',true);
            getEmpData();
        }else{
            $('#empIDTxt').val($('#empIDTxt').val()+$(this).val());
        }
    }
    if(mainTimeout){clearInterval(mainTimeout)}else{console.log('no timeout var set');};
    var mainTimeout = setInterval(function(){setTimeClckState('default');}, 15000);

});

function setTimeClckState(state){
    switch(state){
        case "default":
            $('.timeClckControls input[type=text]').val('');
            $('.timeClckControls input[type=button]').prop('disabled',false);
            $('#statusDiv .alert').removeClass('alert-warning');
            $('#statusDiv .alert').removeClass('alert-success');
            $('#statusDiv .alert').addClass('alert-secondary');
            $('#statusDiv .alert').html(' ');

            $('#clockInOutBtn').removeClass('btn-warning');
            $('#clockInOutBtn').removeClass('btn-success');
            $('#clockInOutBtn').addClass('btn-secondary');
            $('#clockInOutBtn').prop('disabled',true);
            $('#clockInOutBtn').val('CLK');

            $('#clearBtn').removeClass('btn-warning');
            $('#clearBtn').removeClass('btn-success');
            $('#clearBtn').addClass('btn-secondary');
            $('#clearBtn').prop('disabled',true);
            break;
        case 'clockedIn':
            $('#clearBtn').prop('disabled',false);
            $('#clockInOutBtn').prop('disabled',false);

            $('#clockInOutBtn').removeClass('btn-success');
            $('#clockInOutBtn').addClass('btn-warning');
            $('#clockInOutBtn').val('OUT');
            break;
        case 'clockedOut':
            $('#clearBtn').prop('disabled',false);
            $('#clockInOutBtn').prop('disabled',false);

            $('#clockInOutBtn').addClass('btn-success');
            $('#clockInOutBtn').removeClass('btn-warning');
            $('#clockInOutBtn').val('IN');
            break;
    }
}


Your code should work fine:您的代码应该可以正常工作:

 function setTimeClckState(str) { console.log(str); } var mainTimeout = setInterval(function(){setTimeClckState('default');}, 500); $(".timeClckControls input[type=button]").click(function(){ if(mainTimeout){ clearInterval(mainTimeout) } else { /** * The return value of setInterval is just a unique id you use to pass back to * clearInterval. It's not a structured object with any additional information, * nor does it get set to null when you call clearTimeout. So even its cleared * it will never be falsy */ console.log('no timeout var set'); } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="timeClckControls"> <input type="button" value="click me" /> </div>

Okay I figured it out.好吧,我想通了。 Thanks to @Mischa, helped me realize what was happening.感谢@Mischa,帮助我意识到发生了什么。 Problem was that I'm resetting the variable from within a function each time.问题是我每次都从 function 中重置变量。 So the variable actually ends up not having global scope.所以变量实际上最终没有全局 scope。 Googled "how to define global variable from within function".谷歌搜索“如何从函数内定义全局变量”。 Turns out the best way is to set "window.myVar" from inside function.事实证明,最好的方法是从 function 内部设置“window.myVar”。 Ended up just making one function to stop and restart the interval:最终只制作了一个 function 来停止并重新启动间隔:

function stopStartClearInt(){
    if(window.mainTimeout){clearInterval(window.mainTimeout)}else{console.log('no timeout var set');};
    window.mainTimeout = setInterval(function(){
        setTimeClckState('default');
        console.log('Interval check');
    }, 5000);
}

I can run this from literally anywhere in my script and it will work!我可以从脚本中的任何位置运行它,它会起作用!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM