Reputation: 177
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
Upvotes: 7
Views: 2372
Reputation: 72857
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.
Upvotes: 8
Reputation: 741
What about using jQuery delay?
Sample:
$("#container").fadeIn().delay(amoutOfTimeInMiliseconds).fadeOut();
Your function:
function showMessage(message) {
$(".messageText").text(message);
$(".message").fadeIn("slow").delay(5000).fadeOut("slow");
}
It should work... Regards.
Upvotes: 4