Reputation: 20962
I have following JQuery code. I trying to get the click to reset the setInterval so the timer starts again. eg: resets to 5 seconds. So if its counted 4 seconds and I click it should reset to a new full 5 seconds.
var varTimerSpeed = 5000;
bannerDisplayMembersMatchingCriteriaUpdateTimerInterval();
function bannerDisplayMembersMatchingCriteriaUpdateTimerInterval() {
var varTimerInterval = setInterval(function () {
bannerDisplayMembersMatchingCriteriaUpdate();
}, varTimerSpeed);
}
$('#mainBannerOurTopSuggestionsIMG').click(function() {
clearInterval(varTimerInterval);
bannerDisplayMembersMatchingCriteriaUpdateTimerInterval();
});
I can see the click event is working (by writing to console) however it doesn't appear the reset the setInterval. Is there something I'm missing here?
thankyou
Upvotes: -1
Views: 30
Reputation: 1750
var varTimerSpeed = 5000;
var varTimerInterval;
function bannerDisplayMembersMatchingCriteriaUpdateTimerInterval() {
varTimerInterval = setInterval(function () {
bannerDisplayMembersMatchingCriteriaUpdate();
}, varTimerSpeed);
}
$('#mainBannerOurTopSuggestionsIMG').click(function() {
if( typeof(varTimerInterval) != 'undefined')
clearInterval(varTimerInterval);
bannerDisplayMembersMatchingCriteriaUpdateTimerInterval();
});
bannerDisplayMembersMatchingCriteriaUpdateTimerInterval();
try it?
Upvotes: 1
Reputation: 585
var varTimerInterval is locally scoped to the bannerDisplayMembersMatchingCriteriaUpdateTimerInterval function.
try declaring it above as you did with varTimerSpeed;
Upvotes: 1
Reputation: 388446
It is because of the scope of the variable varTimerInterval
, you have declared it to be a local variable in the bannerDisplayMembersMatchingCriteriaUpdateTimerInterval
method, so it will not be available in the click
handler.
Since you need to access the same variable varTimerInterval
in 2 different methods, you need to declare it in a scope shared by both of those functions so that both of the will access the same instance.
var varTimerSpeed = 5000,
varTimerInterval;
bannerDisplayMembersMatchingCriteriaUpdateTimerInterval();
function bannerDisplayMembersMatchingCriteriaUpdateTimerInterval() {
varTimerInterval = setInterval(function () {
bannerDisplayMembersMatchingCriteriaUpdate();
}, varTimerSpeed);
}
$('#mainBannerOurTopSuggestionsIMG').click(function () {
clearInterval(varTimerInterval);
bannerDisplayMembersMatchingCriteriaUpdateTimerInterval();
});
Upvotes: 1