简体   繁体   English

JavaScript jQuery间隔中的全局变量

[英]global variable in javascript jquery interval

I have got code like this 我有这样的代码

var challegneListener;

$(document).ready(function(){
    var challegneListener = setInterval("challengeListenerBot()",5000);
});

function challengeListenerBot(){
    clearInterval(challegneListener);
}

And the problem is that the interval does not stop, becouse function called challengeListenerBot does not see challegneListener variable as number of interval. 问题在于间隔不会停止,因为称为ChallengeListenerBot的函数没有将challegneListener变量视为间隔数。 I must use jQuery to start interval when the document is ready. 准备好文档后,我必须使用jQuery来启动间隔。

Change this: 更改此:

$(document).ready(function(){
    var challegneListener = setInterval("challengeListenerBot()",5000);
});

To this: 对此:

$(document).ready(function(){
    challegneListener = setInterval("challengeListenerBot()",5000);
});

The problem is you're declaring inside your anonymous function, called when the DOM is ready, a new challengneListener variable. 问题是您要在DOM准备就绪时在匿名函数中声明一个新的challengneListener变量。 It hides the global variable, and only saves the setInterval ID to the local variable, which is garbage collected when its enclosing function has finished executing. 它隐藏了全局变量,并且仅将setInterval ID保存到局部变量,该局部变量在其封闭函数完成执行时被垃圾回收。

$(document).ready(function(){
var challegneListener = setInterval("challengeListenerBot()",5000); 
});

Using var inside this function creates a new variable that is scoped to this function, meaning that the challegneListener variable that is defined globally remains undefined hence the interval not being cleared. 在此函数内部使用var会创建一个范围限定于此函数的新变量,这意味着全局定义的challegneListener变量将保持未定义状态,因此不会清除间隔。 Remove the var to fix this code. 删除var以修复此代码。

You hide the global variable, remove the var : 您隐藏全局变量,删除var

$(document).ready(function(){
    challegneListener = setInterval("challengeListenerBot()",5000); 
    // removed the var keyword, because it hides the global var.
});

Another thing, your code uses eval , change it to this: 另一件事,您的代码使用eval ,将其更改为:

challegneListener = setInterval(challengeListenerBot, 5000); 

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

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