Reputation: 5458
I have an alert popup which appears when a certain action takes place. After 5 seconds the alert popup is hidden, using setTimeout()
.
The problem I am having is, if I trigger the popup multiple times, sometimes the subsequent popups appear but disappear straight away. This, I believe is because the previous timeout is still in progress.
I have tried to cancel the timeout using clearTimeout()
but this doesn't make any difference. See code below:
function showAlert() {
var elem = $('#alert');
var alertTimeout;
elem.addClass('active');
if (alertTimeout) {
clearTimeout(alertTimeout);
}
alertTimeout = setTimeout(function() {
elem.removeClass('active');
}, 5000);
}
What's the correct way to do this?
Upvotes: 0
Views: 79
Reputation: 1075735
Your alertTimeout
variable goes away when the function returns. You need to move it outside the function:
var alertTimeout; // <==========================
function showAlert() {
var elem = $('#alert');
elem.addClass('active');
if (alertTimeout) {
clearTimeout(alertTimeout);
}
alertTimeout = setTimeout(function() {
elem.removeClass('active');
}, 5000);
}
Side note: Ideally, this code is in a module or a scoping block where you use let
instead of var
(ES2015+) or a scoping function (ES5 and earlier) so that alertTimeout
and showAlert
aren't global.
If for some legacy support reason showAlert
has to be global, you can still keep alertTimeout
from being global like this:
var showAlert = (function() {
var alertTimeout;
return function showAlert() {
var elem = $('#alert');
elem.addClass('active');
if (alertTimeout) {
clearTimeout(alertTimeout);
}
alertTimeout = setTimeout(function() {
elem.removeClass('active');
}, 5000);
};
})();
(Note that that means showAlert
is no longer hoisted.)
Upvotes: 3