I am trying to make a custom pop up message, that appears, displays to the user for 5 seconds and then fades out. This works fine BUT if the use triggers the event multiple times and the time out is already running the message quickly disappears.
My function so far...
function showMessage(message) {
$(".messageText").text(message);
$(".message").fadeIn("slow");
closeBox = function(){
$(".message").fadeOut("slow");
}
clearInterval(closeBox);
setInterval(closeBox, 5000);
}
Many thanks
Try this:
var interval;
function showMessage(message) {
$(".messageText").text(message);
$(".message").fadeIn("slow");
if(interval){ // If a interval is set.
clearInterval(interval);
}
interval = setInterval(closeBox, 5000);
}
function closeBox(){
$(".message").fadeOut("slow");
}
You need to assign the return of setInterval
to a variable. This handle can be used to end the interval with clearinterval
. (You can't clear a interval by function, only by interval handle)
Also, I pulled the closeBox
function out of the showMessage
function, it's not necessary to declare it every time showMessage
is called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With