JQuery Pop up message - javascript

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.

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.

Related

is there a way to delay a window.onload event?

I am trying to create a pop-up that automatically appears after a delay. is this possible through javascript? if so how would I implement this into my code?
Here is a link to the code I am working on https://jsfiddle.net/hk2808/7cs4xdmg/
function openPopup() {
window.location.hash = 'openModal';
}
window.onload = openPopup;
You can use setTimeout. I would make a more generic function that runs on onload and simply call openPopup from there.
Try this:
function openPopup() {
window.location.hash = 'openModal';
}
function onPageLoad() {
setTimeout(() => {
openPopup()
}, 3000)
}
window.onload = onPageLoad;
The popup will load 3 seconds after the onload for example.
setTimeout will do what you are looking to do
https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout
No, there isn't a way to delay the window onload. You could try to add a lot of images and other things that take a long time to load, but that's not an ideal solution. Instead, you can use setTimeout to make code run after a period of time.
setTimeout(function(){
window.location.hash = 'openModal';
//or whatever else you want to happen after 1 second
},1000);
//the 1000 means after 1000 miliseconds, or after 1 second.
Hope this helps!

Javascript fire the last event

I'm coding a web application and I don't know how to keep on what I'm trying to do with Javascript.
I have a function that is fired when I do zoom on a map or when I move the map. I try to avoid this function do its stuff until it's been a while (2 seconds, for example). Ok, I can use a setInterval method to achieve it.
But what I want and I don't know how to do is... if I do zoom 3 times, very close in time between them, I just want to process the last zoom, not the two previuos ones. I mean, the 2 first function callings have to be cancelled, or something like that.
How could I do that?
Example (pseudo-code) of what I have:
function doStuff() {
setInterval(function({
// do some stuff here...
}, 2000);
}
myMap.on('dragend', doStuff); // If I move inside the map
myMap.on('zoomend', doStuff); // If I do zoom on the map
What I´d try is to set capture the intervalID in a global varial everytime you start your interval; then when you fire the event you check if the variable is set, if it is, you use the clearInterval function to cancel the previous interval before starting the next one.
Something like this:
var intervalID = 0;
function doStuff(){
if(intervalID != 0){
window.clearInterval(intervalID);
}
intervalID = setInterval(function({
// do some stuff here...
intervalID = 0; // try reseting the intevalID on completion, not sure if here
}, 2000);
// Your stuff
https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval
https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval
You could use a object.addEventListener('load', function())-function.
The function inside it will fire after the object has loaded.

Wrong use of Javascript setInterval()

I have a function called using setInterval of JavaScript, which in some scenarios is called multiple times without the interval gap defined (I suspect this is because the intervals are not cleared properly and I'm creating multiple intervals, but I'm not sure).
I can not reproduce the problem locally.
The code uses Twirl but it's basically JS:
function refreshCheckInRequests() {
if (interval) { // If there is an interval running stop it.
clearInterval(interval);
}
jsRoutes.controllers.ExtranetSecuredController.findPendingCheckInRequests("#gymId").ajax({ // Ajax call using Play Framework
success: function (data) {
$("#checkin-request-container").html(data);
addRowListeners()
},
error: function (data) {
if (data.status == 401) {
errorSwitchGym("#Messages("extranet.switch.gym")");
//location.reload();
}
else {
unexpectedError(data)
}
},
complete: function() {
interval = initInterval(); // At the end of the call init the interval again
}
});
}
function initInterval() {
return setInterval(function () { refreshCheckInRequests(); },
20000);
}
var interval;
refreshCheckInRequests();
$("#checkin-request-refresh").click(function (event) {
refreshCheckInRequests();
event.preventDefault();
});
I could use setTimeout instead because at the end, I always call refreshCheckInRequests once, I stop the interval, and at the end I create a new one.
If I use timeout I have to call again my function at the end of the execution of the callback of timeout (like I'm doing right now). If something goes wrong, my callback will never be called again.
Anyway, I would like to know what's going on here. Am I missing something? Am I doing something wrong? Any suggestions?
You're clearing the current interval every time refreshCheckInRequests is called, but there is a delay between when refreshCheckInRequests is called and the new interval is assigned. Because refreshCheckInRequests also runs when an element is clicked, the following scenario could result in an unterminated interval:
User clicks, current interval is cleared, asynchronous findPendingCheckInRequests runs
User clicks again, no interval currently exists (nothing to clear), another asynchronous findPendingCheckInRequests runs
Response from first findPendingCheckInRequests comes back. complete handler runs, interval is assigned to the new interval
Response from second findPendingCheckInRequests comes back. complete handler runs, interval is assigned to the new interval over the old interval
The first created interval remains running, but there no longer exists a reference to it, so that first interval continues repeating forever.
So, try clearing the interval at the moment you reassign interval, ensuring that every new interval will always clear the old one, if an old one is running:
complete: function() {
clearInterval(interval);
interval = initInterval();
}

What is the correct way to do an infinite loop that calls a method in Jquery or Javascript?

I have a page that I want to update non stop, every few seconds.
For this, I wrote the following:
var to;
$(function () {
to = setTimeout(updateDivContent, 2000);
});
function updateDivContent() {
$('#topbox').load('/home/blabla', null);
$('#leftgraph').load('/home/blabla', null, function () {
to = setTimeout(updateDivContent, 2000);
});
};
This worked, however, it leads to what I presume is a memory leak as after around 15 minutes, the computer almost freezes up with the browser taking up all available memory and CPU.
I am guessing that the Timeout is basically stacking, but, I am not sure how to fix this. I have tried getting rid of the second timeout and putting the first one inside a while(true) loop, but, I just couldn't get it to work.
Can anyone suggest anything?
This looks fine actually. But if the first Ajax call does not finish within two seconds, it will stack, and this could (don't know for sure) cause problems.
The timeout itself does not stack, since you are initiating a new one only after the previous one finished.
Try to initiate a new timeout once both Ajax requests finished:
$.when($('#topbox').load('/home/blabla'),
$('#leftgraph').load('/home/blabla')
).then(function () {
setTimeout(updateDivContent, 2000);
});
Reference: $.when
I think it is better to use setInterval instead of setTimeOut.
See this post.
You probably want to call clearTimeout to invalidate the previous timer, like this:
clearTimeout(to);
to = setTimeout(updateDivContent, 2000);
can you this it will call ever 2 second
to = setInterval("updateDivContent", 2000);
function updateDivContent() {
$('#topbox').load('/home/blabla', null);
$('#leftgraph').load('/home/blabla', null, function () {
//to = setTimeout(updateDivContent, 2000);
});
};
Try setInterval:
var to;
$(function () {
to = setInterval(updateDivContent, 2000);
});
function updateDivContent() {
$('#topbox').load('/home/blabla', null);
$('#leftgraph').load('/home/blabla')
};

Javascript - Stop a repeating function [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to pause a setTimeout call ?
I have a function that gets called on page load which starts off a repeating function:
setTimeout(function () {
repeat();
}, 8000)
This function calls repeat() every 8 seconds, inside this function I have a bit of ajax which updates a counter on the page. Clicking on the counter gives the user a drop down menu with a number of messages. The counter value equals the number of messages the user has. Kind of like Facebook notifications.
When clicking the drop down menu Im using jQuery to hide and show it:
$('#messages').click(function () {
$('#messagesDropDown').slideDown();
})
.mouseleave(function () {
$('#messagesDropDown').slideUp();
});
When the #messagesDropDown is visible I want to stop the repeat() function, to prevent the list of messages from updating while Im viewing the current ones.
On .mouseleave I want to start the repeat() function again.
Anyone have any ideas how I can 'STOP' a repeating function In the .click function and start it again on .mouseleave ?
setTimeout returns a ID of the timeout. You can store that value, and then use clearTimeout to stop the timeout when you want.
var timeout;
$('#messages').click(function () {
$('#messagesDropDown').slideDown(function () {
clearTimeout(timeout); // Cancel the timeout when the slideDown has completed.
});
})
.mouseleave(function () {
$('#messagesDropDown').slideUp();
clearTimeout(timeout); // Cancel incase it's still running (you can also set `timeout` to undefined when you cancel with clearTimeout, and apply some logic here (`if (timeout == undefined)` so you can leave it running rather than restarting it)
timeout = setTimeout(repeat, 8000); // Store the ID of the timeout
});
setTimeout will not set a recurring event; it will only fire once (like a delayed event). Look at setInterval (and clearInterval) instead.
You said that this code starts a repeating function:
setTimeout(function () {
repeat();
}, 8000)
Since setTimeout doesn't repeat, I assume that the repeat function itself fires off another setTimeout to call itself again after it runs (chained setTimeout calls).
If so, you have two options:
Have a control variable telling repeat whether to do its work or not. A simple boolean will do. Set the boolean when you want repeat to skip its work, and have repeat check it. This is the dead simple answer.
Have control functions for repeat, like so:
var repeatHandle = 0;
function startRepeat() {
if (!repeatHandle) {
repeatHandle = setTimeout(repeatTick, 8000);
}
}
function repeatTick() {
repeatHandle = 0;
repeat();
}
function stopRepeat() {
if (repeatHandle) {
clearTimeout(repeatHandle);
repeatHandle = 0;
}
}
...and then use them to control the repeats. Be sure to modify repeat to call startRepeat to schedule its next call rather than calling setTimeout directly.

Categories