tags:

views:

58

answers:

2

I have an asp.net page where two grid views are available showing current stock market price updates. I need to update these two grid views every 20 seconds. So I was thinking of using JQuery to do this job.

What I need is a timer which will fire every 20 seconds, send an ajax request to the servers, bring the order lists from the server using json and then update those two grid views. If a request to the server is still being served 20 seconds after it is fired, then I want the old one to be aborted without causing any trouble.

I already know how to bring objects using json. I just need to figure out how to send a request every 20 seconds and cancel a request if it is still being server for 20 seconds.

+1  A: 

Use javascript's

setTimeout("doSomething()",1000);
gmcalab
If I use that method, would I be able to cancel an old request when a new one fires?
Night Shade
Sure, you could set a hidden field that toggles a request. Then check to see what the value of the hidden field is before calling `setTimeout`, if the value is `false` then you will skip the request, if the value is `true` then go ahead with the request.
gmcalab
Ok, I will try :)
Night Shade
+2  A: 

Use javascript's setInterval() to run some code at an interval.

jQuery's $.ajax() will return the XMLHTTPRequest object that you can abort.

var request;    // Stores XMLHTTPRequest object

setInterval(function() {
                 // if there's a current request, abort
              if(request) request.abort();

                // make ajax request, and assign request to variable
              request = $.ajax({
                     // My ajax request parameters
              });

}, 20000);       // repeat every 20 seconds (20,000 milliseconds)

http://api.jquery.com/jQuery.ajax/


EDIT:

If you ever need to stop the interval from running, you need to assign the interval to a variable, and then clear it whenever you want.

var theInterval = setInterval(function() {...}, 20000);

theInterval.clear();   // To stop the interval from running
patrick dw
This is a far better way of implementing this compared to what I posted. +1
gmcalab
@gmcalab - Thanks. The ability to abort an ajax request is really a nice option to have.
patrick dw
@gmcalab:Ya, I agree too. +1 for this answer.
Night Shade