I have called a JavaScript function on<body onload>event where there is a while loop which will iterate unless and until the desired response is fetched from a PHP page.
However since the loop will make a very frequent set of requests, that is causing my browser to hang.
Is there another easy way where we can perform AJAX function request evry 15 minutes without causing much load on the browser?
use setInterval that calls your function every 15 min. something like this:
setInterval(function(){
// Call to your function that performs an ajax call...
}, 15 * 60 * 1000);
Here is link to setInterval documentation:
http://www.w3schools.com/jsref/met_win_setinterval.asp
You could use a jquery plugin for polling.
https://launchpad.net/jquery.poll
var ajax_call = function () {
$.ajax(options);
};
setInterval(ajax_call, interval);
to clear it use
clearInterval(ajax_call);
Weel i think you can use setTimeout() like this
setTimeout(yourajaxfunction,90000);
// 900000 is the delay in millisecond, after that your function is called.
inside your loop so that the function is executed only when the timeout ends.
P.S.
i think ajax was born to be "responsive", you should refresh things responding to an action of the user and not with a timeout in my opinion! :)
Related
I would like to put a delay after a button is pressed in order for the button to load the data from the cache before executing the next line of code. Would putting a sleep be the best way to do this?
Something like this or is there an alternative approach to best solve this problem?
setInterval(document.getElementById("generateButton"), 1000);
Don't use setInterval to do this. It doesn't have the functionality you seem to desire (it repeats). Instead, use jQuery and do something like this:
$("#generateButton").click(function(event){
setTimeout(function(){
//Do what the button normally does
}, 1000);
});
Or (without JQuery):
var generateButton = document.getElementById("generateButton");
generateButton.addEventListener("click", function(){
setTimeout(function(){
//Do what the button normally does
}, 1000);
});
Using setTimeout over setInterval is preferred in your case because setTimeout runs only once while setInterval runs multiple times.
I assume you have, in your html, <button id='generateButton' onclick='someFunction()'>Button Text</button>. Remove the onclick='someFunction() and put your someFunction() where I said (in the examples) "Do what the button normally does."
You can also add in the code that loads the cache a method that calls another method once the cache has been loaded (when the someFunction() from the button is called, it loads the cache, and at the end of the function (set this up using callbacks), once the cache has been loaded, it calls another method onCacheLoaded() that can be run once the cache has been loaded.
You should use callbacks, so the moment you loaded data from cache you can call it and continue executing the rest of the script.
You cannot use interval since you cannot be sure how much time is needed for the data to load. Though keep in mind the asynchronous nature of javascript and don't block the part of the script that does not depend on the data that's being loaded.
Try setTimeout:
myButton.addEventListener('click', function() {
setTimeout(delayed, 1e3); // Delay code
}, false);
function delayed() {
// Do whatever
}
Note setInterval runs a function periodically, setTimeout only once.
Also note that the delayed code must be a function (or a string which will be evaluated, but better avoid that). However, document.getElementById("generateButton") returns an html element (or null).
I am working on an application that sends current timestamp to database every 2 minutes with AJAX using setInterval.
But somehow setInterval stops after some minutes (i didnt calculate the exact time), but i believe it happens when i dont open that browser's tab for 20-30 minutes.
function tmstmp() {
$.post("send_functions.php?act=time");
}
$(function() {
setInterval(tmstmp, 60000);
});
Is that normal that setInterval stops if that tab is not on foreground ?
If yes, how can i prevent setInterval to stop ? or check if it stopped ?
Thanks
You should try to make an function call on page startup:
test();
and then loop that function:
function test() {
setTimeout(function() {
// your code
test();
}, 2000);
}
That's not supposed to happen.
Browsers may indeed reduce the timer resolution to something around 1/s, but not clear the setInterval.
Could there be some bug in your code that causes a clearInterval?
No code + no debug information = hard to tell what went wrong.
Just to be sure add the following line to the code (method) that gets executed with setInterval and watch after 20-30 minutes if you still get output in the console.
console.log('Yep! I am alive!');
EDIT: Could be anything but try changing the tmstmp method to include a callback function after the POST request gets executed. That way you'll at least know that it works.
function tmstmp() {
$.post("send_functions.php?act=time", function(data){
console.log('Yep! I am alive!');
});
}
How to send Ajax request on every 1s using JQuery ?
You probably don't want to send a request every second as David already noted.
Therefore, using setInterval is a bad idea.
Instead consider doing something like this:
function doAjax() {
$.ajax({
...
complete: function() {
setTimeout(doAjax,1000); //now that the request is complete, do it again in 1 second
}
...
});
}
doAjax(); // initial call will start rigth away, every subsequent call will happen 1 second after we get a response
you can use setInterval, but setInterval ist not part of jQuery:
setInterval(function() {
$.get(...);
}, 1000);
The interval 1 sec is small enough and it can be that you will start the second request before you receive response to the first request. So you should either start the next request after receiving of the previous one (see the suggestion of Martin Jespersen) or save jqXHR from the previous $.ajax request in a variable and use it to abort the previous request (see here an example)
setInterval(myAjaxCall, 1000);
Obviously in the function myAjaxCall() you will do all you ajax stuffs with jquery.
if you use setInterval method, you may crush the browser, because setInterval is not waiting for ajax function to complete, if server is running slow or user's connection speed is low this may be cause running multiple ajax requests at the same tme
I have a php page that echos out rows from a database. I want to call it via jquery/ajax every 30 seconds. But I also want to be able to call the page at any time so that if I add a record via the form, once the form submits I want the page via called to ajax to update the results right away. Can anyone point me in the right direction or provide some base code so I can try to figure this out? Still very new to jquery/ajax.
If you want to set something on a timer, you can use JavaScript's setTimeout or setInterval methods:
setTimeout ( expression, timeout );
setInterval ( expression, interval );
Where expression is a function and timeout and interval are integers in milliseconds. setTimeout runs the timer once and runs the expression once whereas setInterval will run the expression every time the interval passes.
So in your case it would work something like this:
setInterval(function() {
//call $.ajax here
}, 5000); //5 seconds
As far as the Ajax goes, see jQuery's ajax() method. If you run an interval, there is nothing stopping you from calling the same ajax() from other places in your code.
If what you want is for an interval to run every 30 seconds until a user initiates a form submission...and then create a new interval after that, that is also possible:
setInterval() returns an integer which is the ID of the interval.
var id = setInterval(function() {
//call $.ajax here
}, 30000); // 30 seconds
If you store that ID in a variable, you can then call clearInterval(id) which will stop the progression.
Then you can reinstantiate the setInterval() call after you've completed your ajax form submission.
I have a piece of Javascript that checks for a condition (via an AJAX call) every n seconds. If that condition is true, it stops checking. I have implemented it in the following way:
var stopTimer;
var timerId = setInterval(function() {
/* Make Ajax Calls and set stopTimer */
if (stopTimer) {
clearInterval(timerId);
}
}, 10000);
However, I find erratic behaviour: Works sometimes, but at other times, it keeps checking forever. I have checked that (as much as is possible) there is no error in any part of the code.
I am therefore suspecting that calling clearInterval inside a setInterval handler might be the culprit. Is that right? Is it OK to call clearInterval inside a setInterval handler?
Thank you for your attention
It's safe. The issue is probably to do with stopTimer not being set as you expect.
I don't think there will be any issue with your code unless the AJAX function is erroneous. You have to take care of the success and error callbacks of the AJAX function so that there won't be any issue with the loop not being stopped.
Also I think you are constantly polling the server for a response and then doing the appropriate action. You can use Reverse AJAX to do this kind of process.
Make sure you're not inadvertently re-using the same timer name elsewhere in your code which would result in you always stopping the second timer to be defined.
Either give the timer a unique name, or scope it to a function
var timerForAjax = setInterval(function() {
/* Make Ajax Calls and set stopTimer */
if (stopTimer)
{
clearInterval(timerForAjax);
}
}, 10000);
I was careless enough to call my timer interval and didn't realize I was creating two timers in the same scope both called interval. Blamed iOS8 for about an hour until I realized that that was nothing to do with it.