View Full Version : Waiting on/with Javascript

14 Jun 2010, 7:22 AM
It could be that with this question I am exposing my ignorance to JavaScript and Ext, but if so, then hopefully it can yield a simple response!

I am using 3rd party server software and client-side JavaScript that I would like to avoid modifying as much as possible. There is a JavaScript function, calc_data(), that sends an async command to the server. After it sends the request, this function generates a JavaScript polling function to asynchronously query when the server is finished, at which point, it calls a data_available() JavaScript function, which updates the web page. Fine.

I want to utilize this mechanism with my own send/receive JavaScript to load an Ext.Tree with the data from the server. So, with my JavaScript, I can generate my own calc_data() function that sends the message to the server and I can override the data_available() function to know when the data is available to the client. That is to say, I can send the request in one function and get another function called when I can retrieve the data. The problem is, with a "load()" or "get_data()" type of JavaScript function, I need to idle until the data_available() function is called. The 3rd party software is already taking care of communication with the server, so I do not need to run any php or generate any AJAX code, but yet I still need to wait for the data.

How can I make a get_data() function in JavaScript that can sleep/defer/wait/pause and then resume when another function gets called without burning cpu cycles in a while loop?


14 Jun 2010, 7:48 AM
Javascript on most browsers is inherently mono-threaded, so you cannot use a wait/notify pattern

Instead you use callbacks.

At the lowest level you can use the Javascript HTTPRequest object to fetch data.

Many libraries have convenience functions that build on top of it and make such calls more convenient.
(eg JQuery http://api.jquery.com/jQuery.get/)

14 Jun 2010, 8:07 AM
Thanks for the response, Cyberqat.

These examples still send http requests, which I'm hoping to avoid because I really don't need to. (My calc_data() function already made a call to the server to get it going and my data_available() JavaScript function will be called when complete.)

14 Jun 2010, 8:14 AM
Well, im not sure what your looking for. As I say, there is no multi-threading in Javascript. So, if you want to poll and do something else between polls you need to build a loop that does that. If you want to poll every N seconds you need tp use a callabck on a Javascript timer. (http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/)