stopping setTimeOut(); [duplicate] - javascript

This question already has answers here:
How to stop a setTimeout loop?
(10 answers)
Closed 8 years ago.
please help with getting a right function or method to stop the setTimeout function.
I've been trying with the following codes but the setTimeout "loop" could not be stopped.
What i'm trying to do is to get the user's current location every 5 seconds, and then when i press the stop button. It stops getting the location.
function geoTrackstart(){
//geolocation code
});
timer = setTimeout(geoTrackstart, 5000);
}
function geoTrackstop(){
clearTimeout(geoTrackstart);
timer = 0;
}

I think you want to use like this:
function geoTrackstart(){
//geolocation code
});
timer = setTimeout(geoTrackstart, 5000);//set timer
function geoTrackstop(){
clearTimeout(timer);//clear the timer
//setTimeout(geoTrackstart,5000);//set timeout if you want to run again
}

If you're polling for the geo i'd use a interval rather than a timeout so that it's run every 5 seconds until you stop it, this way you don't have to create a new timeout every 5 seconds -- unless you wanted to create the timeouts manually.:
var geoFetchInterval;
function geoTrackstart(); {};
//if you want it to run immediately the first time
geoTrackStart();
//start the interval
geoFetchInterval = setInterval(geoTrackStart, 5000);
function getTrackStop() {
clearInterval(geoFetchInterval);
};
//assuming jquery
$('#stop-button').on('click', getTrackStop);

Related

How do you stop setInterval from creating multiple instances on .load()'s? [duplicate]

This question already has answers here:
How to stop all timeouts and intervals using javascript? [duplicate]
(10 answers)
Closed 3 years ago.
When a user clicks a nav button on my site they call a .load(), i.e., $("#main_window").load("file.php"); If file.php contains JavaScript along with a setInterval timer then if a user clicks the nav button multiple times they'll create multiple setIntervals. How do I stop this and only have one timer at all times?
Obtaining the ID of the timer doesn't help because .load resets global variables. Thus I'm unable to prevent multiple timers on repeated .load().
var myVar;
console.log(myVar); // will be undefined when .load() calls this file again.
myVar = setInterval(reload, 5000);
console.log(myVar); // A new ID will be created on each .load(), but all old instances will continue to fire
function reload() {
$(tableName).DataTable().ajax.reload(null, false);
console.log("reloaded");
}
Console.log output: with two .loads():
undefined
27
undefined
34
if(myVar){
clearInterval(myVar)
}
var myVar;
console.log(myVar); // will be undefined when .load() calls this file again.
myVar = setInterval(reload, 5000);
console.log(myVar); // A new ID will be created on each .load(), but all old instances will continue to fire
function reload() {
$(tableName).DataTable().ajax.reload(null, false);
console.log("reloaded");
}

Delay first function call for n-seconds [duplicate]

This question already has answers here:
Why is the method executed immediately when I use setTimeout?
(8 answers)
Closed 6 years ago.
I'm having a javascript function which I have set an interval to execute every 30 seconds. This is my code:
function ping() {
// code ...
}
ping(); // call function when page loads for first time
// call function every 30 seconds
window.setInterval(function(){
ping();
}, 30000);
What I'd like to do is to delay the first call (right when the page loads for first time) for 5 seconds and then the function should execute again every 30 secs.
I have tried the setTimeout, but doesn't seem to work, it executes imidiatelly any ideas what I'm doing wrong ?
setTimeout(ping(), 5000); // delay first call for 5 secs
// call function every 30 seconds
window.setInterval(function(){
ping();
}, 30000);
I guess you are not waiting until timeout to declare the interval function.
There is a few different ways to do that, so let me suggest one:
function ping() {
// code ...
}
setTimeout(function () {
ping(); // call function when page loads for first time
// call function every 30 seconds
window.setInterval(function(){
ping();
}, 30000);
}, 5000);
You are calling it immediately on setTimeout(ping(), 5000);. You are setting the result of ping() as the timeout function. If you want ping to be called by the timeout, then either do setTimeout(ping, 5000); or wrap it in a closure, like you did the second time.

Aborting a JavaScript setTimeout function [duplicate]

This question already has answers here:
how to kill a setTimeout() function
(5 answers)
Stop scheduled JavaScript execution
(4 answers)
Closed 9 years ago.
The title may be misleading, but it's essentially what I need to accomplish.
I have an AJAX "Loading" text that I want to update if the server has taken more than 15 seconds to respond.
Here is the code:
$(".loader").html('Loading');
$(".loader").show();
setTimeout(function () {
if ($('.loader').is(":visible")) {
$(".loader").html('Click here to reload.</span>');
}
}, 15000);
Is there a better approach? When I eventually call $(".loader").hide(); I want the setTimeout counter to be aborted. Is it possible?
Sure. setTimeout returns a value you can pass to clearTimeout in order to stop timeout.
var handle = setTimeout(function () {
alert("Oh noes, I ran!")
}, 5000)
clearTimeout(handle)
You can use the clearTimeout function:
$(".loader").html('Loading');
$(".loader").show();
var timerId= setTimeout(function () {
if ($('.loader').is(":visible")) {
$(".loader").html('Click here to reload.</span>');
}
}, 15000);
$(".stop").click(function () {
clearTimeout(timerId);
$(".loader").html("done");
});
See this fiddle: http://jsfiddle.net/KaNUP/
I would recommend to make a shorter period (1 sec) and increment counter inside function you call. Then you can exit on successfull load or counter threshold, whichever comes earlier.

JavaScript setTimeout() duplicates

I'm fairly new to JavaScript/jQuery, but have made a script to change the background picture.
First Script
The first script version works fine and does the following:
creates a setInterval timer that calls function backgroundChange() to run every 7 seconds
decides the next picture URL
sets the background picture
This works great, but the problem is when the website is live, on a slow connection the background picture doesn't load in time for the next timer change.
New Script
So the new version:
creates a setTimeout timer that calls function backgroundChange() to run after 7 seconds
var theTimer = setTimeout(backgroundChange, 7000);
clearsTimeout (surely I shouldn't have to run this?)
window.clearTimeout(theTimer);
decides the next picture URL
waits until the picture is loaded:
then sets the background picture
then adds a new setTimeout timer
$('#testImage').attr('src', imageText).load(function()
{
$('#backgroundTop').fadeIn(timeIn,function()
{
theTimer = setTimeout(backgroundTimer, 7000);
});
});
The problem is that the timer now seems to be called double the amount of times whenever the timer runs and exists in the .load function.
I havent purposely not posted my code yet, as I want to make sure my understanding is correct first, rather than someone just fixing my code.
Ta very much.
Instead of unbinding, you could use a JavaScript closure for the timer function. This will maintain a single timer that is reset every time it is called.
var slideTimer = (function(){
var timer = 0;
// Because the inner function is bound to the slideTimer variable,
// it will remain in score and will allow the timer variable to be manipulated.
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
Then in your code:
$('#testImage').attr('src', imageText).load(function() {
$('#backgroundTop').fadeIn(timeIn,function()
{
slideTimer(backgroundTimer, 7000);
});
});
There should be no need to clear or set the timer anywhere else in your code.
You need to unbind the load handler before you add the next one, since they keep piling up as your code stands. With every iteration, you add an extra handler that does the exact same thing. Use unbind to remove the old handler before you reattach:
$('#testImage').unbind('load');

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