JQuery AJAX: prevent the delay caused due to set interval function [duplicate] - javascript

This question already has answers here:
JavaScript: How to get setInterval() to start now? [duplicate]
(3 answers)
Closed 6 years ago.
I am keeping a live track on no. of users in my system, for that I am using javascript's setInterval() function, following is the code:
function fetchdis() {
$.ajax({
url: "/count/dist",
dataType: "json"
}).success(function(data){
$('#val_dis').html(JSON.stringify(data.sum));
});
}
setInterval(function () {fetchdis()}, 3000);
everything is working properly except I am getting a delay of 3 seconds also first time when I am loading the data(resulting into an empty space), I do not want that interval the first time the data loads.
Thank you for your help

That's because setInterval executes the callback every 3 seconds, and you haven't called the function anywhere else.
function fetchdis() {
$.ajax({
url: "/count/dist",
dataType: "json"
}).success(function(data){
$('#val_dis').html(JSON.stringify(data.sum));
});
}
fetchdis();
setInterval(function () {
fetchdis();
}, 3000);
Notice that I'm calling fetchdis() right before I register the interval.

Related

what are ways to preform javascript loops [duplicate]

This question already has answers here:
What's the easiest way to call a function every 5 seconds in jQuery? [duplicate]
(7 answers)
Closed 8 years ago.
How do I get this javascript to run every second?
source code:
<script type="text/javascript">
$(function() {
//More Button
$('.more').live("click",function() {
var ID = $(this).attr("id");
if(ID) {
$("#more"+ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "ajax_more.php",
data: "lastmsg="+ ID,
cache: false,
success: function(html){
$("ol#updates").prepend(html);
$("#more"+ID).remove();
}
});
} else {
$(".morebox").html('no posts to display');
}
return false;
});
});
</script>
Use setInterval() to run a piece of code every x milliseconds.
You can wrap the code you want to run every second in a function called runFunction.
So it would be:
var t=setInterval(runFunction,1000);
And to stop it, you can run:
clearInterval(t);
Use setInterval:
$(function(){
setInterval(oneSecondFunction, 1000);
});
function oneSecondFunction() {
// stuff you want to do every second
}
Here's an article on the difference between setTimeout and setInterval. Both will provide the functionality you need, they just require different implementations.
You can use setTimeout to run the function/command once or setInterval to run the function/command at specified intervals.
var a = setTimeout("alert('run just one time')",500);
var b = setInterval("alert('run each 3 seconds')",3000);
//To abort the interval you can use this:
clearInterval(b);
window.setTimeout(func,1000);
This will run func after 1000 milliseconds. So at the end of func you can call window.setTimeout again to go in a loop of 1 sec. You just need to define a terminate condition.
Reference
You can use setInterval:
var timer = setInterval( myFunction, 1000);
Just declare your function as myFunction or some other name, and then don't bind it to $('.more')'s live event.
Use setInterval(func, delay) to run the func every delay milliseconds.
setTimeout() runs your function once after delay milliseconds -- it does not run it repeatedly. A common strategy is to run your code with setTimeout and call setTimeout again at the end of your code.

jquery sleep not executing on ajax reques

I have an Ajax request waiting for response from another process.
function test() {
var flag = 0;
while (flag === 0) {
$.ajax({
url: "cs/CheckForProcess",
async: false,
success: function(data) {
if (data !== 'NotReady') {
$('#results').html(data);
flag = 1;
} else {
$('#results').html('<h1>Processing...</h1>');
setTimeout(function() {
}, 6000);
}
}
});
}
}
the problem is that the setTimout isnt working although i see in debug mode that the else condition is executed.
EDIT:
i want the next ajax request to be sent only 6 seconds after validating the process is not ready.
what am i missing?
Thx.
setTimeout is an async function. It does not pause your script. Your script will continue to run (and 6000ms later your setTimeout callback function will execute).
You could consider using setInterval to keep checking for your other condition to be true.
You could probably remove async:false by keeping track of your server response elsewhere. Once you have a successful callback then you should cancel the interval.
function test() {
var timerId = 0,
timerId = setInterval(function(){
$.ajax({
url: "cs/CheckForProcess",
success: function(data) {
if (data !== 'NotReady') {
$('#results').html(data);
clearInterval(timerId);
}
}
});
}, 6000)
}
Javascript does not have the ability to sleep (e.g. suspend or block javascript execution) using setTimeout.
A setTimeout() schedules a function to run sometime in the future and other javascript just happily keeps running during that time.
What you should do is use setTimeout() to schedule the next run of your ajax function if the data was not yet ready. So, when there is no data ready, you schedule the next ajax call for 6 seconds from now, but when you do get the data, you just process the data and you're done.
In addition, you really don't want to use async: false because that freezes the browser (doesn't allow any other processing to occur) during the ajax call. This same operation can be written to leverage the asynchronous nature of ajax and allow you to still solve your problem, but allow other processing to continue in the browser with no browser blocking. This requires asynchronous programming techniques.
You can do so like this:
function test() {
function runIt() {
$.ajax({
url: "cs/CheckForProcess",
async: true,
success: function(data) {
if (data !== 'NotReady') {
$('#results').html(data);
} else {
// if data not ready yet, then put up some progress
// and call this again in 6 seconds
$('#results').html('<h1>Processing...</h1>');
setTimeout(runIt, 6000);
}
}
});
}
// start the first iteration
runIt();
}
The setTimeout function takes a function to execute after the timeout. You are passing an empty function. So, after 6 seconds, that empty function is executing - and obviously not doing anything.
I think you are expecting setTimeout to delay the execution of other scripts on your page. This is not the case, as setTimeout delays and executes the supplied callback function in a new thread (not blocking other execution on your page).
If you are trying to do something after 6 seconds, just supply the code inside of the function() {} code you have. Eg:
setTimeout(function() {
$.ajax(...);
}, 6000);
or
setTimeout(runIt, 6000);
Links:
setTimeout documentation (mozilla)
Related SO question

How to Handle delays that made by multiple timeouts (containing ajax calls)

Consider I have multiple (sometimes more than 12) ajax calls that are calling every 2 seconds or more. Data gathered through the calls are set to the UI contained elements (Like progress bars). After all I have delay on SCROLL while timers working . This delay is natural, But How can I handle it?
NOTE: Calls Destinations are services that provides data with the minimum spent time. The point that makes the scroll sad, is using multiple setTimeout() and setInterval() methods. To get more familiar with my work, See the below code:
function FillData(accessUrl, name) {
var add = accessUrl;
$.support.cors = true;
if (add) {
$.ajax({
type: 'GET',
url: accessUrl,
crossDomain: true,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
Update(name, data);
},
error: function (xhr, status, error) {
LogResponseErrors(status , error, name);
}
});
setTimeout(function () { FillData(accessUrl, name); }, interval);
//Consider that the method calls with different parameters one time and it will run automatically with setTimeout
}
else {
freezeFrame(name);
}
}
Used Tags explains what I used.
Any useful answer will be appreciated
From what I understand in your question. You have delay when you're handling your ajax responses and you need to remove the delay.
Javascript is single-threaded. Therefore, if there is a function that takes long time to complete, it could dominate the thread and cause the UI not responding. To deal with this, you have 2 options:
Optimize your code so that the function does not take long.
Use setTimeout to break your function into smaller pieces. For example: if your function is executing a loop of 100 items, you could break it to execute 10 times with 10 items each.
Update: (based on updated question):
It seems that the loop never stops when you use setTimeout like this. Should have something like:
counter++;
if (counter <= 12)
setTimeout(function () { FillData(accessUrl, name); }, interval);
Due to timing problem between ajax and your setTimeout, at some points, there are a lot of events (escalated) waiting in the queue to be executed and cause performance problem. Try putting your setTimeout inside your success or complete function

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.

Issue with setTimeout in ajax based polling using jquery [duplicate]

This question already has answers here:
Why is my function call that should be scheduled by setTimeout executed immediately? [duplicate]
(3 answers)
Closed 8 years ago.
In my code i need to poll a url after every 5 seconds using ajax . The URL returns a json response. Below is the code that i wrote inside $(document).ready to do this. But,the setTimeout() function does not work. The startPoll() function is called immediately after the response is received.I want to halt for 5 seconds after response is received before calling the startPoll function again . Any way to fix this ?
$(document).ready(function(){
var startPoll = function() {
$.post('<url>', {},onPollRequestComplete, 'json');
}
var onPollRequestComplete = function(response) {
responseObject = eval(response);
if(responseObject.success) {
//Do something here
}
setTimeout(startPoll(),5000); /*Make next polling request after 5 seconds*/
}
startPoll();
});
Thank You
This is your problem:
setTimeout(startPoll(),5000);
You're calling startPoll immediately, not after 5 seconds. Instead, you should pass in the function reference, like so:
setTimeout(startPoll,5000);
If you want the polling to fire every 5 seconds even if previous polls didn't work (a server error was encountered), you should use setInterval instead. The code you have now is great if you want to be able to stop polling in case of errors.
I think rather than setTimeout you need to use setInterval
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var startPoll = function() {
$.post('url', {}, function(response) {
var responseObject = eval(response);
if (responseObject.success) {
alert('hi');
}
}, 'json');
}
setInterval(startPoll, 5000); /*Make next polling request after 5 seconds*/
});
</script>
</head>
<body>
</body>
</html>

Categories