How to send Ajax request on every 1s using JQuery? - javascript

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

Related

Are asynchronous javascript HTTP requests sent before or after the main stack completes

assume the following:
http.get('mycoolwebsite.com/somecontent', function(){
console.log('printed');
}
doSomeReallyIntensive100Hourwork();
I understand that we will see the word 'printed' printed on the console after 100 hours.
The questions:
Does javascript delay the request after 100 hours and then execute the callback or does it send out a request immediately and schedule the callback to print later? Basically, do we immediately notice the network request or not?
do we immediately notice the network request or not?
That's up to the browser. JS will immediately tell the browser that it should execute the following request, but it's up to the browser to decide wether it has the capacity to immediately start this request or wether to queue it untill there are ressources available.
Then, eventually the request is sent, the response is there, and the browser will notify JS that the request is done, and pass the recieved data. Then JS, as soon as JS is idle*, it will call the callback-function.
JS is single-threaded. It can't run two pieces of code at once, and it won't interrupt some other code to run your callback-function. It will call it as soon as there is no other pending Javascript to run.
The request is initiated immediately, and the response will possibly also have arrived, but your get callback function will be triggered by an event in the event queue which only gets processed in the next task.
From mdn on XMLHttpRequest.send(), the method that is executed under the hood of the http.get method:
The XMLHttpRequest.send() method sends the request. If the request is asynchronous (which is the default), this method returns as soon as the request is sent.
Note the last part. See also the WHATWG standards, section 4.5.6:
The send(body) method must run these steps:
10.4.1 Wait until either req’s done flag is set or
the timeout attribute value number of milliseconds has passed since these subsubsteps started
while timeout attribute value is not zero.
... so the method does wait to make sure the request has been sent (or a timeout occurred).
Here is a demo with an HTTP call to a service that answers after a 2 second server-sided wait. You can launch it in two ways: with or without the intensive work.
When using the option to not do the work, the response comes back about 2 seconds after the click. If using the other option (with the work), then the work is done after three seconds and the response is processed immediately afterwards (have some patience after clicking):
function work() {
// Be busy for 3 seconds
var until = performance.now() + 3000;
while (performance.now() < until);
console.log('hard work done');
}
function test(work) {
$.get("http://httpstat.us/200?sleep=2000", function() {
console.log('response processed');
});
if (work) work();
}
$('#without').click(test.bind(null, null));
$('#with').click(test.bind(null, work));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="with">Request with 3 secs of work</button>
<button id="without">Reguest without that work</button>

Second jQuery.post request finishing before first one. How to avoid this?

I'm trying to implement a search bar like facebook for my website users. While you type the name, some results are displayed.
To avoid sending a request for each button pressed, i've setup a timeout. The idea is: if i'm going to type jack It doesn't make sense to search for j, ja, jac, jack, but it's better to wait for the users finishes typing before sending any request.
Once the request is sent and completes, a div called mydiv is filed with results (the request response). If after some time long enough i type another letter, another request is sent and mydiv is filled with new results.
The idea comes from this question.
Here is my simplified implementation.
var thread = null;
$('#search-user').keyup(function() {
clearTimeout(thread);
name = $('this').val(); //i get the name just typed
thread = setTimeout(function(){
get_data_with_ajax_and_put_it_in_mydiv(name);
}, 200);
});
function get_data_with_ajax_and_put_it_in_mydiv(name){
$.post()....
/*Do some stuff*/
}
As you can see, after a 200ms timeout the function get_data_with_ajax_and_put_it_in_mydiv(); is called. This function, emptys mydiv before putting new data. It works almost always, but sometimes a strange bug occurs.
I'm going to explain where i think the problem is, by providing a real example. Let us assume that get_data_with_ajax_and_put_it_in_mydiv() takes from 50ms to 1000ms to complete, depending on various factors (network speed, congestion, etc...).
At t=0 i type jac and i stop typing.
At t=200 the timeout expires and get_data_with_ajax_and_put_it_in_mydiv() runs. In this case it takes 1000ms to run
At t=210, because i'm a slow writer, i type the letter k of jack. mydiv is empty because
the first request has not yet completed.
At t=410 the timeout for the letter k epires and a second request
is sent. This time, the function takes 100ms to run.
At t=510 the second request finishes and i get the results for jack.
At t=1200 the first request finishes and i get the results for jac.
ERROR
As you can see due to impredictability of time elaped by ajax requests i got a wrong result. mydiv is filled with jac results and not jack.
SOLUTION
The first solution that came to my mind is the following: every time i call get_data_with_ajax_and_put_it_in_mydiv() i have to stop any previous request still running. How can i do that? If not possible, how can i fix this error?
Why not use a debounced function to handle the ajax call?
http://benalman.com/code/projects/jquery-throttle-debounce/examples/debounce/
You should use the Promise interface and use the 'done' method to chain these two operations sequentially
http://api.jquery.com/jquery.post/

Do we need setTimeout for short polling?

If I want to implement short polling like this:
function firstCall(){
$.ajax({
...
success: function(response){
if (response.OK == "OK"){
secondCall();
}else{
firstCall();
}
}
});
}
Will this be enough? or do I really need to surround the firstCall() in else clause with setTimeout ?Thanks
I recommend you to use a little timeout, because now you are creating a lot of traffic to your server. Ajax is fast and success will be executed very often.
So I recommend you to use setTimeout or setInterval instead!
This solution relies on the first call to be a success. If at any point in time your code doesn't "succeed" (perhaps there was a server hiccup?), your "polling" will stop until a page refresh.
You could use setInterval to call that method on a defined interval, which avoids this problem:
setInterval(function(){
$.ajax({}); // Your ajax here
}, 1000);
With both solutions, your server will be handling a lot of requests it might not need to. You can use a library like PollJS (shameless self plug) to add increasing delays, which will increase performance and decrease bandwidth:
// Start a poller
Poll.start({
name: "example_poller",
interval: 1000,
increment: 200,
action: function(){
$.ajax({}); // Your ajax here
}
});
// If you want to stop it, just use the name
Poll.stop("example_poller");
You need setTimeout() if you want to reduce requests to server
you'll need to setTimeout if you don't want to wait to user action or ajax response to trigger an event after a certain time, otherwise you may do wait for the ajax call success or error events.

Detecting When Javascript is Done Executing

Is there an event in javascript that I could bind some sort of listener to that will tell me when all javascript/jQuery/Ajax is done executing on the page? The page will not be loading/unloading/reloading, etc between the time the execution begins and the time that I need the listener to "listen", so those events don't work. The page literally is not doing anything. The button is clicked and some javascript functions fire which contain Ajax calls to web services. After all have finished, I want to change window.location. But window.location is changing before the web services have finished in my case.
Currently using setTimeout to achieve this, but as sometimes the code needs more time to run than normal, sometimes the window.location is firing before all the other javascript has finished. Simply put
<input type = "button"... onclick="doThis();";
function doThis() {
try{
//Contains AJAX calls to web services which is mainly what screws up my timing since it may still be trying to execute stuff when the redirect statement happens
}
catch (e) {
}
//Currently doing setTimeout(redirect, 10000);
//Would like to simply detect when all of the above is done and then redirect.
}
Edit: Left out a crucial piece of info. The AJAX calls are in a for loop. The use of variables and success callbacks hasn't been working so well for me as by the time my success callback is executing, my variables have taken on new values in the for loop.
What you are trying to achieve is a classical concurrent programming problem. It is solved by the use of a barrier.
To put it simply, you need to:
Count how many calls you've done.
Set a callback on all AJAX completion events.
Make that callback decrement the number of calls.
The callback checks whether the number of calls has reached zero or not. If yes, then your final code (here, redirect) is called.
The actual implementation is left as an exercise to the reader :)
Hint: embed AJAX calls into a function that handles all counter incrementation and callback setting.
What I do:
Create a variable that represents the number of outstanding AJAX calls.
Before making an AJAX call, increment the variable.
At the end of the code that completes an AJAX call, call a function (e.g. ajaxComplete).
ajaxComplete should decrement the count. When it reaches zero, you know all your calls are complete.
Assuming you're using jQuery.ajax, it sounds like you're looking for ajaxStop.
Why don't you try using something like the Underscore library's after function in the callbacks?
var done = _.after(3, function() {
window.location = 'http://example.com';
});
$.ajax({
url: '/tic',
success: function() {
done();
}
});
$.ajax({
url: '/tac',
success: function() {
done();
}
});
$.ajax({
url: '/toe',
success: function( data ) {
done();
}
});
You should check for the response from AJAX call, and only in that response do redirect. This way you will avoid doing redirect while AJAX was still executing.

How to call an AJAX function after every 15 seconds?

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! :)

Categories