Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and the Yahoo Answers website is now in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
How do you serialize asynchronous activities in JavaScript?
What is the best way to serialize activities between asynchronous JavaScript code? Tight loops that wait for a global variable to be set are too CPU-intensive. Using a timer is too artificial and is not guaranteed to work. Is there any way to use an operating system semaphore? If not, is there any way to create a semaphoring system within JavaScript?
2 Answers
- 9 years agoFavorite Answer
You set an event handler on the object you're calling that returns asynchronously. There's really nothing you can do in javascript that's async without calling a method on some object -- timers are no exception. (When you call setTimeout, you're implicitly calling window.setTimeout.) So even if you could create a semaphore, or any other O/S synchronization object, it wouldn't be of any use because you can't create a thread.
An event handler is just a function, below is an example, using AJAX. In this example, the object req must be global so that it's visible inside of rscHandler.
// somewhere in global code...
var req = new XMLHttpRequest;
req.open("GET", url, true);
req.onreadystatechange = rscHandler;
req.send();
// ... script ends/returns control to host
function rscHandler() {
// handle event
if (req.status == 200) {
//...
}
}
btw, I'm not sure I follow your logic about timers, they work just fine if used correctly. If, by async activities you actually mean a single activity, from within which you want to yield the processor one or more times before it completes, timers are your only option, short of a Java applet or ActiveX.
- petittLv 44 years ago
"How does AJAX cut back the site visitors between the server and customer?" truly of fresh (resending) the entire web page (which could be hundreds of ok if there are portraits), AJAX facilitates you to deliver purely the request to the server, and get lower back purely the information to get replaced - which may be some bytes. for occasion, in a internet site that does unit conversions, you enter a length in inches. You click post. the information going to the server is the size you entered and, in all probability a single byte designating the gadgets to transform to and from. The server sends lower back a quantity, that's some bytes. (Javascript asynchronously gets that information and modifications the information in an ingredient on the web page to demonstrate it.)