How can I run jQuery load() request each n seconds? - javascript

I have following code
$('document').ready(function() {
reload();
});
function reload() {
$('div#info').load('http://somesite.ru/script.php');
setInterval(reload(), 10000);
}
but seems like method reload() runs too fast. Firefox shows me message, about jquery.min.js is sems to busy. How can I make part of page refresh one time for each 10 seconds?

You should remove the (), also put the setInterval function outside the context of the reload function.
function reload() {
$('#info').load('http://somesite.ru/script.php');
}
$(document).ready(function() {
setInterval(reload, 10000);
});

Replace:
setInterval(reload(), 10000);
with:
setInterval(reload, 10000);

Use setTimeout() instead it is safe and performance wise good than the setInterval() to fulfill your requirement.
var time= setTimeout(reload,1000);
after checking certain conditions in the reload() method call the setTimeout inside it again
function reload()
{
/// your logic
setTimeout(reload,1000);
}
use the above variable to destroy the interval whenever you don't want to reload anymore
clearTimout(time);

Refer: http://www.w3schools.com/js/tryit.asp?filename=tryjs_setinterval
setInterval(function(){reload();},10000);

Another way is just use
$('document').ready(function() {
setInterval(function() {
$('div#info').load('http://somesite.ru/script.php');
}, 10000);
});
All works fine. Thanks a lot for your answers.

Related

How can I automatically change a page in Javascript?

Trying to get the code to automatically change page using setTimeout, but I do not get it to work.
setTimeout()(page3, 500);
function page3() {
changepage3('automatic')
}
This is what my code looks like right now, but I am suspecting that this is not enough. Anyone knows what is missing?
try this one
function page3() {
changepage3('automatic')
}
setTimeout(page3, 500);
setTimout needs a specific syntax to work, check it out on the best JavaScript documentation by Mozilla: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#Syntax
Here is an example
saySomethingAfter(5);
function saySomethingAfter(second) {
setTimeout(saySomething, second * 1000);
}
function saySomething() {
console.log("Something");
}
Your question is "How can I automatically change a page in Javascript?" using setTimeout. Let's analyse the needs:
change a page → open a new URL (cf. Open URL in same window and in same tab)
automatically using setTimeout → with the correct syntax
function changePage(url) {
window.open(url, "_self");
}
function changePageAfter5sec(url) {
setTimeout(function() {
changePage(url)
}, 5000);
}
changePageAfter5sec("https://stackoverflow.com")
Another way using beautiful functional JavaScript:
function changePage(url) {
return () => {
window.open(url, "_self");
}
}
function changePageAfter(second) {
return (url) => {
setTimeout(changePage(url), second*1000);
}
}
const changePageAfter5sec = changePageAfter(5);
changePageAfter5sec("https://stackoverflow.com")
You have 2 major problems in the code snippet provided:
That is not correct setTimeout() syntax - thus it doesn't actually work.
Even if it did work, it would call 1 function that uses another function which doesn't exist thus breaking the code.
fix problem number 1:
window.setTimeout(changePage, 5000);
now we have a running timeout that will trigger 5000 milliseconds after initiation(usually).
so let's fix problem 2 and let changepage() call an actual proper url opening function:
function changePage(){
window.open(urlOfPage3);
}
Finally a simpler version with an anonymous callback function in the setTimeout:
window.setTimeout(function(){
window.open(urlOfPage3);
}, 5000);

cordova setTimeout function

I'm encountering a problem with setTimeout, and I can't figure out why.
I'm using cordova, and the setTimeout function leads to curious comportment.
app.displayData = function(device) {
app.readThermometer(device);
app.readAccelerometer(device);
app.readHumidity(device);
app.readMagnetometer(device);
//setTimeout(app.displayData(device), 5000);
};
This is executed once.
app.displayData = function(device) {
app.readThermometer(device);
app.readAccelerometer(device);
app.readHumidity(device);
app.readMagnetometer(device);
setTimeout(app.displayData(device), 5000);
};
This is executed many times, but way faster than once every 5 seconds. It is a problem for me because it prevent jQuery from executing correctly. (Never getting the dom modification expected)
What am I missing? If it is a bug in cordova, do you know other way to delay code execution in javascript?
You're calling the function app.displayData directly
setTimeout(app.displayData(device), 5000);
Try the following instead
setTimeout(function () {
app.displayData(device);
}, 5000);
And another alternative if you prefer Function.bind
setTimeout(app.displayData.bind(app, device), 5000);

How to add .delay to .click on .each iteration (jquery)

So, I want to put delay on this JavaScript code.
$(function(){
$('.clickThis').each(function(){
$(this).click();
});
});
I tried this
$(function(){
$('.clickThis').each(function(){
$(this).click().delay(5000);
});
});
above script doesnt work .
Is there any alternative?
I've tried Google it but I still couldn't figure it out, because I have little knowledge in JavaScript.
This will do it:
$(function(){
$('.clickThis').each(function(i, that){
setTimeout(function(){
$(that).click();
}, 5000*i );
});
});
Here's a version using a recursive setTimeout loop.
$(function() {
var click = $('.clickThis').toArray();
(function next() {
$(click.shift()).click(); // take (and click) the first entry
if (click.length) { // and if there's more, do it again (later)
setTimeout(next, 5000);
}
})();
});
The advantage of this pattern over setTimeout(..., 5000 * i) or a setInterval call is that only a single timer event is ever queued at once.
In general, repeated calls to setTimeout are better than a single call to setInterval for a few reasons:
setInterval calls can queue up multiple events even if the browser isn't active, which then all fire as quickly as possibly when the browser becomes active again. Calling setTimeout recursively guarantees that the minimum time interval between events is honoured.
With setInterval you have to remember the timer handle so you can clear it
You need to write an asynchronous setTimeout loop, for more information http://www.erichynds.com/javascript/a-recursive-settimeout-pattern/
Try to use this:
$(function () {
var items=$('.clickThis');
var length=items.length;
var i=0;
var clickInterval=setInterval(function(){
items.eq(i).click();
i++;
if(i==length)
clearInterval(clickInterval);
}, 5000);
});
var $clickthis=$(".clickthis");
var i= -1;
var delayed = setInterval(function(){
if (++i < $clickthis.length) $clickthis.eq(i).trigger("click");
else clearInterval(delayed);
}, 5000);
I am not sure but I think that setTimeout function should do the trick.
See here https://developer.mozilla.org/en-US/docs/DOM/window.setTimeout
Try
$(function(){
$('.clickThis').each(function(_,i){
var me=$(this);
setTimeout(function(){me.click()},5000*i);
);
});

how to reload javascript code block

I need to reload a block of javascript every amount of time.. say
<script type="text/javascript">
var frame = some sort of code;
</script>
i need that block of any function to be reloaded every 15 seconds without reloading the page itself .. something like jQuery time out but i don't know how to apply it..
any idea?
var frame;
setInterval(function() {
frame = someSortOf.Code();
}, 15000);
That will execute the provided function every 15 seconds, setting your value. Note the var frame is declared outside the function, which gives it global scope and allows it to persist after your function executes.
You should not really "reload" a script. What you really want to do is simply run an already loaded script on a set interval.
function foo() {
// do something here
if (needRepeat) {
setTimeout(foo, 15000);
}
}
setTimeout(foo, 15000);
You can use setTimeout('function()', 15000); - put this line of code at the end of the function() so that it calls itself again after 15000ms.
The other way is just to call setInterval('function()', 15000); and this will call your function() every 15000ms.
The difference between the first and the second one is that the first calls the function after specific milliseconds (only once, so you need to insert it in the function itself) and the second one just calls the function every n milliseconds.

Call js-function using JQuery timer

Is there anyway to implement a timer for JQuery, eg. every 10 seconds it needs to call a js function.
I tried the following
window.setTimeout(function() {
alert('test');
}, 10000);
but this only executes once and then never again.
You can use this:
window.setInterval(yourfunction, 10000);
function yourfunction() { alert('test'); }
window.setInterval(function() {
alert('test');
}, 10000);
window.setInterval
Calls a function repeatedly, with a
fixed time delay between each call to
that function.
Might want to check out jQuery Timer to manage one or multiple timers.
http://code.google.com/p/jquery-timer/
var timer = $.timer(yourfunction, 10000);
function yourfunction() { alert('test'); }
Then you can control it with:
timer.play();
timer.pause();
timer.toggle();
timer.once();
etc...
setInterval is the function you want. That repeats every x miliseconds.
window.setInterval(function() {
alert('test');
}, 10000);
jQuery 1.4 also includes a .delay( duration, [ queueName ] ) method if you only need it to trigger once and have already started using that version.
$('#foo').slideUp(300).delay(800).fadeIn(400);
http://api.jquery.com/delay/
Ooops....my mistake you were looking for an event to continue triggering. I'll leave this here, someone may find it helpful.
try jQueryTimers, they have great functionality for polling
http://plugins.jquery.com/project/timers
You can use setInterval() method also you can call your setTimeout()
from your custom function for example
function everyTenSec(){
console.log("done");
setTimeout(everyTenSec,10000);
}
everyTenSec();
function run() {
window.setTimeout(
"run()",
1000
);
}

Categories

Resources