Kamil Solarczyk
Kamil Solarczyk

Reputation: 62

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. I must use jQuery to start interval when the document is ready.

Upvotes: 1

Views: 2239

Answers (3)

Declan Cook
Declan Cook

Reputation: 6126

$(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. Remove the var to fix this code.

Upvotes: 1

gdoron
gdoron

Reputation: 150253

You hide the global variable, remove the 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:

challegneListener = setInterval(challengeListenerBot, 5000); 

Upvotes: 0

Paul Bruno
Paul Bruno

Reputation: 1906

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. 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.

Upvotes: 4

Related Questions