Delay first function call for n-seconds [duplicate] - javascript

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.

Related

stopping setTimeOut(); [duplicate]

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);

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 doesn't work [duplicate]

This question already has answers here:
Why is my function call that should be scheduled by setTimeout executed immediately? [duplicate]
(3 answers)
Closed 7 years ago.
I wanted a JavaScript function to run 60 seconds after page is loaded.
After a little research I have made, I've found that setTimeout() is the solution.
So that's what I did:
<body onLoad="setTimeout(postAction('news.reads', 'article'), 60000);">
Somehow, setTimeout does not work. After the page is loaded, there's no need to wait 60 seconds because postAction() runs immediately.
Why is it happening? How to solve it? Are there alternatives to setTimeout() up there?
Thank you!
You need to wrap postAction in a function to defer execution:
setTimeout(function() { postAction('news.reads', 'article'); }, 60000);
You are actually executing postAction immediately, your code is equivalent to:
var result = postAction('news.reads', 'article');
setTimeout(result, 60000);
The correct way to do what you want in JS, ie setting a timeout after the page is loaded:
(function(w)
{
var load = function()
{
setTimeout(postAction,60000);
if (w.removeEventListener)
{//remove listeners, to avoid leak...
return w.removeEventListener('load',load,false);
}
return w.attachEvent('onload',load);
};
if (w.addEventListener)
{
return w.addEventListener('load',load,false);
}
return w.attachEvent('onload',load);
}(this));
Instead of window.onload = function(){setTimeout(postAction,60000);};, which will work, too, but cause a mem-leak in IE <9. That's just for completeness' sake
Anyway, the key line here is setTimeout(postAction,60000);
Update
After seeing the code you're using, this is the easiest fix:
<body onLoad="setTimeout(function(){ return postAction('news.reads', 'article');}, 60000);">
Are you using setTimeout like :
setTimeout(function(){alert("OK");}, 1000 * 60); // alert "OK" in 60s
<script>
function doSomeJavascript() {
// javascript code goes here
alert('5 secs is up!');
}
// calls function doSomeJavascript() 5 secs after page load
var interval = setInterval(doSomeJavascript, 5000);
setTimeout(function() {
window.clearInterval(interval);
}, 5000);
</script>

Javascript setTimeout function repeat

Is there a way to repeat a function in Javascript using the setTimeout function? For example, I need two functions to be called every five seconds. I have something like this:
$(document).ready(function(){
setTimeout('shiftLeft(); showProducts();', 5000);
});
but it only happens once, five seconds after page loads, and I need it to happen every five seconds.
Use setInterval() instead of setTimeout(), if you want your function to be executed repeatedly. setTimeout() delays the execution of your function for x seconds, while setInterval() executes your function every x seconds.
Both within the boundaries of the event queue of JavaScript, so don't be too confident, that you functions get executed at the exact time you specified
$(document).ready(function(){
setInterval( function(){ shiftLeft(); showProducts(); }, 5000);
});
Every x seconds can be done with setInterval:
$(document).ready(function(){
setInterval(function(){
shiftLeft(); showProducts();
}, 5000);
});
$(document).ready(function(){
setTimeout(function(){
shiftLeft(); showProducts();
}, 5000);
});

how can I execute a javascript program 30 after page loads

how can I execute a javascript program 30 after page loads, and I have to execute it repeatedly in 30 seconds. I would like to use jquery since I already included in my document
Thank you guys
You could use the window.setTimeout method:
window.setTimeout(function() {
// This will execute 30s after the page loads
// and it will execute only once
}, 30000);
If you want to repeat the execution of the function on every 30 seconds you could use the setInterval method.
As far as jquery is concerned you don't need to to use it for such a simple task as it is already built into javascript.
You want setInterval() here, like this:
setInterval(function() {
alert("It's been 30 seconds");
}, 30000);
setInterval() will fire after the delay (so 30 seconds in) then again every time the delay is up (every 30 seconds as desired).
If you want to execute it 30 times, once a second, you'd use setInterval.
var interval = window.setInterval(function() {
// do stuff
}, 1000);
window.setTimeout(function() {
window.clearInterval(interval);
}, 30 * 1000);
$.ajaxSetup({
cache: false
});
setInterval(function() {
$("#data1").load('1.php');
}, 30000);
});
Just substitute your jQuery function in :)

Categories