Javascript fire the last event - javascript

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.

Related

stopping a nested javascript function running more than once

I'm trying to get a javascript function to run only once. I've seen this question has been asked before, e.g. Function in javascript that can be called only once, but I can't get the solutions in here to work. I'm not sure if it's because I've got nested functions, or whether there's something I'm missing. Essentially, I'm trying to run a function which, when a webpage is scrolled, it:
- runs a little animation on a canvas in the header
- reduces the size of the header
- leaves it at that
But when there is any subsequent scrolling, the animation keeps re-running. Here's a summarised version of the non-working code:
$(document).on("scroll",function(){
var arrange_title = function(){
//some code
};
if($(document).scrollTop()>0){
arrange_title();
arrange_title = function(){};
setTimeout(function(){
$("header").removeClass("large").addClass("small");
},1000);
}
});
I've also tried declaring a global variable, setting it to "false" in a "window.onload" function, then set it to true in an if function that runs the animation (the if function running only if the variable is false), but that doesn't stop it either. Thoughts?
What you're looking for is something along the lines of listenToOnce where the listener fires the one time, but never again. This could be modified to a number of calls, but the logic is like so:
Register the listener.
Then once the listener fires, remove it.
See .off
$(document).on("scroll",function(){
var arrange_title = function(){
//some code
};
if($(document).scrollTop()>0){
arrange_title();
arrange_title = function(){};
setTimeout(function(){
$("header").removeClass("large").addClass("small");
// $(document).off('scroll'); // or here
},1000);
}
$(document).off('scroll'); // remove listener, you can place this in the setTimeout if you wish to make sure that the classes are added/removed
});
Don't use a time out. That is why you are getting in trouble. Declare a variable outside of your function using var, that will make it global. Your code should be inside of a check for that variable. Before executing your code the first time but inside of the check, change that variable so that the code will never run again.
Try avoid setTimeout. Almost all animation can be watched for end.
function doHeaderAnimation() {
return $('header').animate();
}
function makeHeaderSmall() {
$("header").removeClass("large").addClass("small");
}
function handleScroll(event) {
if ($(document).scrollTop() > 0) {
doHeaderAnimation().then(makeHeaderSmall);
$(document).off("scroll", handleScroll);
}
}
$(document).on("scroll", handleScroll);

jQuery while object.hasClass

I'm trying to find a way to stop a function at a certain point until something does not have a specific class anymore. I cannot change the place where this class is being assigned and removed because it's a plugin.
I was thinking of doing something like this
function DoSomething() {
while ($('div.divControl').hasClass('playing'))
{
//Wait here
}
};
Is this the correct way to go?
This will block so the element will never be changed, as no other code will execute.
What you need to use is an interval:
var interval = setInterval(DoSomething, 500);
function DoSomething() {
if ($('div.divControl').hasClass('playing'))
{
// Do something
clearInterval(interval);
}
};
This will execute the function every half second. The interval will be cancelled after the function succeeds.
No, that will just hang the browser as it goes into an infinite loop.
Your best bet (as best I can think at the moment anyhow) is to do a setTimeout on the function and have it check to see if it your div still has the class every quarter of a second or so.
Still, not nice at all =[

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.

setTimeout in loop to check for a change in bounds

This is my code:
var b;
while(!b){
setTimeout(function(){
alert('sss')
b=1;
}, 500);
}
and it will not alert 'sss'
What can i do?
Updated:
I want to get bounds on google maps v3:
function get_bounds(){
var bounds_;
while(!bounds_){
setTimeout(function(){
bounds_=map.getBounds();
if(bounds_){
var leftBottom=[bounds_.getSouthWest().lat(),bounds_.getSouthWest().lng()]
var rightTop=[bounds_.getNorthEast().lat(),bounds_.getNorthEast().lng()]
return [leftBottom,rightTop];
}
}, 500);
}
}
updated2:
hi patrick dw, i don't know why , but your code doesn't work:
var b;
function waitForB() {
setTimeout(function(){
if(!b)
waitForB();
else
alert('sss');
}, 500);
}
waitForB()
updated3:
it is ok now :
var b;
function waitForB() {
setTimeout(function(){
if(!b){
waitForB();
b='ss';
}
else{
alert('sss')
}
}, 500);
}
waitForB()
JavaScript in web browsers is run in a single thread. When you call setTimeout(), it won't spawn a new thread. This means that setTimeout() will not execute until all of your main code has finished executing.
For this reason, you will end up with an infinite loop, because your loop condition is dependant on the execution of the setTimeout() callback.
Here's an interesting article on how JavaScript timers work:
How JavaScript Timers Work by John Resig
UPDATE:
Further to the updated question, you may want to listen to the bounds_changed event instead. I am not sure how you are planning to use your get_bounds() function, but you may want to refactor your logic to use an event listener instead:
google.maps.event.addListener(map,'bounds_changed', function () {
// The code here is triggered when the bounds change
});
That code is going to burn CPU time and memory by scheduling timeouts to happen. Think about it: you're loop condition is "b" becoming truthy. How is that going to happen? Only when a timer event fires. Will that happen? No, because you're eating the whole machine scheduling zillions more timeouts.
This sort of situation has as a tell-tale sign the effect of warming up the room you're sitting in.
I don't know what effect you're trying to get. Why not start by just the setTimeout() call and see how that goes. Maybe you could describe more about what it is you're trying to do.
Maybe you will want to use setInterval instead of setTimeout.
When b is changed, alert shows up.
var b = false;
(function () {
var intervalId;
function wait() {
if (b) {
clearInterval(intervalId);
alert('sss');
}
}
intervalId = setInterval(wait, 500);
})();
It is more intuitive and it doesn't mess with global variables too much.
HINT: Put semicolon after every statement if you are not sure where to omit safely.
This problem can now be solved correctly using the idle rather than the bounds_changed event listener:
google.maps.event.addListener(map, 'idle', function() {
updateStuff();
});
This event is fired when the map becomes idle after panning or zooming.
http://code.google.com/apis/maps/documentation/javascript/reference.html
It also fires after the map is first rendered, so this is probably the only event listener you need on your map in order to keep it up to date.

Watching setTimeout loops so that only one is running at a time

I'm creating a content rotator in jQuery. 5 items total. Item 1 fades in, pauses 10 seconds, fades out, then item 2 fades in. Repeat.
Simple enough. Using setTimeout I can call a set of functions that create a loop and will repeat the process indefinitely.
I now want to add the ability to interrupt this rotator at any time by clicking on a navigation element to jump directly to one of the content items.
I originally started going down the path of pinging a variable constantly (say every half second) that would check to see if a navigation element was clicked and, if so, abandon the loop, then restart the loop based on the item that was clicked.
The challenge I ran into was how to actually ping a variable via a timer. The solution is to dive into JavaScript closures...which are a little over my head but definitely something I need to delve into more.
However, in the process of that, I came up with an alternative option that actually seems to be better performance-wise (theoretically, at least). I have a sample running here:
http://jsbin.com/uxupi/14
(It's using console.log so have fireBug running)
Sample script:
$(document).ready(function(){
var loopCount = 0;
$('p#hello').click(function(){
loopCount++;
doThatThing(loopCount);
})
function doThatOtherThing(currentLoopCount) {
console.log('doThatOtherThing-'+currentLoopCount);
if(currentLoopCount==loopCount){
setTimeout(function(){doThatThing(currentLoopCount)},5000)
}
}
function doThatThing(currentLoopCount) {
console.log('doThatThing-'+currentLoopCount);
if(currentLoopCount==loopCount){
setTimeout(function(){doThatOtherThing(currentLoopCount)},5000);
}
}
})
The logic being that every click of the trigger element will kick off the loop passing into itself a variable equal to the current value of the global variable. That variable gets passed back and forth between the functions in the loop.
Each click of the trigger also increments the global variable so that subsequent calls of the loop have a unique local variable.
Then, within the loop, before the next step of each loop is called, it checks to see if the variable it has still matches the global variable. If not, it knows that a new loop has already been activated so it just ends the existing loop.
Thoughts on this? Valid solution? Better options? Caveats? Dangers?
UPDATE:
I'm using John's suggestion below via the clearTimeout option.
However, I can't quite get it to work. The logic is as such:
var slideNumber = 0;
var timeout = null;
function startLoop(slideNumber) {
//... code is here to do stuff here to set up the slide based on slideNumber...
slideFadeIn()
}
function continueCheck() {
if (timeout != null) {
// cancel the scheduled task.
clearTimeout(timeout);
timeout = null;
return false;
} else {
return true;
}
};
function slideFadeIn() {
if (continueCheck){
// a new loop hasn't been called yet so proceed...
$mySlide.fadeIn(fade, function() {
timeout = setTimeout(slideFadeOut,display);
});
}
};
function slideFadeOut() {
if (continueCheck){
// a new loop hasn't been called yet so proceed...
slideNumber=slideNumber+1;
$mySlide.fadeOut(fade, function() {
//... code is here to check if I'm on the last slide and reset to #1...
timeout = setTimeout(function(){startLoop(slideNumber)},100);
});
}
};
startLoop(slideNumber);
The above kicks of the looping.
I then have navigation items that, when clicked, I want the above loop to stop, then restart with a new beginning slide:
$(myNav).click(function(){
clearTimeout(timeout);
timeout = null;
startLoop(thisItem);
})
If I comment out 'startLoop...' from the click event, it, indeed, stops the initial loop. However, if I leave that last line in, it doesn't actually stop the initial loop. Why? What happens is that both loops seem to run in parallel for a period.
So, when I click my navigation, clearTimeout is called, which clears it.
What you should do is save the handle returned by setTimeout and clear it with clearTimeout to interrupt the rotator.
var timeout = null;
function doThatThing() {
/* Do that thing. */
// Schedule next call.
timeout = setTimeout(doThatOtherThing, 5000);
}
function doThatOtherThing() {
/* Do that other thing. */
// Schedule next call.
timeout = setTimeout(doThatThing, 5000);
}
function interruptThings() {
if (timeout != null) {
// Never mind, cancel the scheduled task.
clearTimeout(timeout);
timeout = null;
}
}
When a navigation element is clicked simply call interruptThings(). The nice part is that it will take effect immediately and you don't need to do any polling or anything else complicated.

Categories