Javascript requests - javascript

I have two checkboxes on selection of each one will raise a ajax request in order to get response from server. I need to call a method only once when there is atleast 2 seconds gap after the last request is made. Any idea? This means i do not want to call the methods when checkboxes are clicked continously for less than 2 seconds gap. How can i cancel the request made if the time gap between the requests in less than 2 seconds. Note that i want the method to be fired only once after the last request is not followed by other requests for 2 seconds.
var timeout;
clearTimeout(timeout);
timeout = setTimeout(function () { // call method }, 2000);

Note that i wan to excecute the method only once for the last request made.
You don't show any code, but assuming you already have a function doAjax() that does the ajax request, you can ensure it isn't called until two seconds after the last click in any two second period by using the setTimeout() function to do something like this:
var timerID;
document.getElementById("yourCheckboxIdHere").onclick = function() {
clearTimeout(timerID);
timerID = setTimeout(doAjax, 2000);
};
Note that doAjax does not have parentheses after it when passed as a parameter to the setTimeout() function.
If you need to pass parameters to your doAjax() function change the line with setTimeout() to:
timerID = setTimeout(function(){
doAjax(parameters, go, here);
}, 2000);

Related

setTimeout ajax throttle not working

I have a timer, and a function that retrieves data everytime the user clicks certain buttons. To avoid rapid succession of retrieving data
So I have a timer
var timer;
Then a function to update something via ajax
function doTheThing(data){
clearTimeout(timer);
$.ajax({
url:'/post/url',
data:data,
}).done(function(data){
timer = setTimeout(function(){
getMoreData();
},2000);
});
}
Theoretically this should start the timer on every request, but if the user successively hits buttons to cause multiple requests, it will clear the last, and start fresh. Inside the timer, I have the getMoreData(), to hopefully only retrieve once, if the user presses buttons 2 or more times successively.
function getMoreData(){
...another ajax request, which I only really want to fire once,
... if the user presses buttons very fast to trigger that first one
}
However, this isn't working. I am getting just as many requests to getMoreData(), as I am button presses.
So my timer isn't working. Whats the deal??
Your current implementation is not working is because you're clearing the timeout in doTheThing(data). There's a delay for every ajax request. So if you click rapidly, the clearTimeout will be called before any setTimeout is registered and basically does nothing.
Consider moving it to your getMoreData method, sample
function getMoreData(){
clearTimeout(timer);
timer = setTimeout(...)
//Your other ajax
}

Why my setInterval function doesn't stop

I need to write a setInterval function in javascript. Thi is the code:
var myTimer=setInterval(function(){
var time=0;
$.ajax({
url:'...'
type: "POST",
dataType:"",
success: function (response) {
if(response=="true" || time>=10000){
clearInterval(myTimer);
}
time=time+1000;
},
error: function () {
alert("FAIL");
}
});
},1000);
I don't know why It doesn't stop in clearInterval. Anyone can help me?
You've claimed that the code does "come in the 'if'", so I assume the clearInterval call is actually being made.
Given that, the most likely explanation is that the interval is being cleared (after all, select isn't broken), but before the first "true" response, you've already made more than one ajax call, and the other ones you're seeing are ones scheduled before the interval was cleared.
E.g., your code runs and:
Fires off ajax call #1, which takes more than a second to complete
Fires off ajax call #2
Ajax call #1 completes but isn't "true"
Fires off ajax call #3
Ajax call #2 completes and is "true", clearing the interval
Ajax call #3 completes
Mixing two separate asynchronous intervals (one via setInterval and one via ajax) is asking for trouble.
If the goal is to make the request once a second and stop when you get back "true", I would have the success handler schedule the next call, e.g.:
(function() {
var time = 0;
var started = 0;
start();
function start() {
started = Date.now();
$.ajax({
url: '...'
type: "POST",
dataType: "",
success: function(response) {
if (response != "true") {
// Schedule the next call to occur one second after we
// started the previous call; or almost immediately if
// the call took more than a second to complete
setTimeout(start, Math.max(0, 1000 - (Date.now() - started)));
}
time = time + 1000;
},
error: function() {
alert("FAIL");
}
});
}
})();
Let me illustrate the expected and the actual scenarios to make things clearer.
Scenario #1
The image below shows the case where all your ajax requests complete before one second. You will notice that ajax callback success (or error) functions will execute only before clearInterval (which is what you always expect).
Scenario #2
When some of your ajax requests take more than one second (which is probably what happens), then your ajax callbacks can fire before / after / before-and-after the clearInterval, which makes you feel that your setInterval doesn't stop.
Note that your time variable is useless because it's a function-scoped variable that you initialize to 0 every function call. And even if it's a global variable, it'll only clear the interval in the 11th success function callback, and nothing guarantees how long these 11 successful requests will take.
Solution
As T.J. Crowder suggested, it's better to schedule the next ajax call in the success callback of the previous one, which guarantees that your ajax requests fire sequentially (only one at a time).
Note: Because you edited your question after his answer, then you'll also need to edit the if condition like this:
success: function(response) {
if (response != "true" && time < 10000) {
setTimeout(start, Math.max(0, 1000 - (Date.now() - started)));
}
}

time period count of multiple settimeout calls

During several ajax requests, dependant functions are being called at certain period of time. My Question is, there any way to find the total time period(200+300+500) without using events in settimeout function.
//main ajax calls using following functions
setTimeout(function(){
avg(10,15,30);
alert('I am triggered at 2ms');//dependant function 1 (calculate avg)
},200);
setTimeout(function(){
total(50,100,30);
alert('I am triggered at 3ms');//df 2(calculate total)
},300);
setTimeout(function(){
vat_cal(180,12.5);
alert('I am triggered at 5ms');//df 3(calculate vat % for total)
},500);
Assuming that I don't know how many times the setTimeout is being used.
So that If time factor is known it makes easier to load the data with notification.
Multiple ajax requests are killing data loading time. If I know the total time (200+300+500 = 1000). I can notify the user to wait upto a second.
function avg(x1,x2,x3)
{
alert(x1+x2+x3)
}
function total(x1,x2,x3)
{
alert(x1+x2+x3)
}
function vat_cal(x1,x2,x3)
{
alert(x1+x2+x3)
}
$.when( avg(10,15,30),total(50,100,30), vat_cal(180,12.5) ).done(function( x,y,z ) {
alert("finish")
});
Your problem seems a bit vague. But if you want to repeat setTimeout() function for a several time, it'll be better to use setInterval() function.
I dont really get the result that you want, but it should work.
[Code is Here][1]
[1]: http://jsfiddle.net/asomani/2y0t60g5/2/
Use When and Then callback method and in the last ajax request complete call the time Calculate Method.
window.time1 = new Date().getTime();
function aCallback()
{
window.time2 = new Date().getTime();
total_time = (window.time2 - window.time1)
}
$.when($.ajax({
data: {test:"1"}
}), $.ajax({
data: {test:"1"}
}),$.ajax({
data: {test:"1"},
success: aCallback
}) ).done(function( x,y,z ) {
alert(total_time );
});

Sending jQuery ajax request on keyboard input

I'm sending an ajax request to the server on user's input to an <input> element, like this:
$('#my-input').bind("input", function(event){
// here's the ajax request
});
What bothers me is that it send unnecessarily many requests on every user's keyup, meaning that if the user types very fast, there are many unnecessary requests. So I get the idea that there should be a certain delay/timeout, which waits a certain time (50 miliseconds?) for the user to stop typing before sending the ajax request. That would be one problem solved.
But what about cases when the first ajax request haven't been completed before sending another request? (Typing 60 ms / char while ajax request taking 300 ms).
What is the best way to solve this problem (both idea- and code-based)?
You can use throttle function in underscore library. As its documentation says:
Creates and returns a new, throttled version of the passed function, that, when invoked repeatedly, will only actually call the original function at most once per every wait milliseconds. Useful for rate-limiting events that occur faster than you can keep up with.
Even if you don't want to introduce a new library, you can still get idea about how this function works from its source code. In fact, a simple version of throttle function could be:
function throttle(func, delay) {
var timeout = null;
return function() {
var that = this, args = arguments;
clearTimeout(timer);
timeout = setTimeout(function() {
func.apply(that, args);
}, delay);
};
}
This jQuery throttle-debounce plugin is also helpful. Especially, the debounce function seems more suitable to your needs than throttle function according to its author:
Debouncing can be especially useful for rate limiting execution of handlers on events that will trigger AJAX requests
You could just use the setTimeout function. Every so often, see if the text hasn't changed, and if it hasn't, then process accordingly.
setTimeout(function() {
// Do something after 1 second
}, 1000);
You can set async: false in your ajax request so it will process second ajax call only after completion of first ajax request.
I'd go with #HuiZeng's answer, but just in case you want a slightly modified version.
Steps
Listen to keydown using a setTimeout that you can clear.
When it fires, check if you have a previous request in queue, if so abort it and fire a new one
Example:
var inputTimer = 0, req;
function onInput(e){
clearTimeout(inputTImer);
inputTimer = setTimeout( function(){
// You have access to e here
// Cancel any previous requests
req && req.abort();
req = $.ajax({/*...Do your magic here :)*/})
}, 100)
}

delay ajax request

What is the best way to set timeout that will force my page not to set more than one ajax request per minute
Thanks in advance!
I'd use a simple variable holding the timerId returned from setTimeout. Something like this:
var timerId;
var doRequest = function(){
if(timerId) return;
timerId = setTimeout(doRequest, 60*1000);
// ajax code here
};
This will throttle the request to once per minute. If you need to stop the setTimeout call, then simply add another boolean based off the user event you are watching for.

Categories

Resources