Ajax, javascript and threads : the final truth

Since I have written Ajax and javascript don’t use thread, one of my reader (BK) told me that I was wrong. Here’s the final truth.

What I said

If javascript runs some code that takes 5 seconds to execute and an ajax response arrives at 2 seconds, it will take 3 seconds before it will be executed (before the callback function is called).

Example. We have a f() function that is incredibly long to execute (5 seconds) because it has a lot of code.

1. function f() is started
2. f() makes an ajax call
3. f() is still executing since 2 seconds
4. the response from the server arrives at the third second
5. f() is still in execution for 3 seconds
6. the callback function for ajax is called

What he said

Briefly, say I have CallPage1, CallPage2 and DoSomething. Both CallPage are async.

CallPage1 called
CallPage2 called
DoSomething called
CallPage1 Returned (DoSomething is now paused)
DoSomething ended
CallPage2 Returned

The DoSomething() function is paused when the ajax response arrives. The callback for the ajax is called and only then, DoSomething() resumes its execution.

That didn’t make sense to me. Javascript is really sequential and it would not do that kind of complex stuff. But, I had to be sure.

The test

I made a simple page to test it all.

1. Loop from 0 to X (user defined). X should be a big number.
2. The first loop, it makes an ajax request
3. The loops will finish someday
4. The callback for the ajax will be called someday

I didn’t know what to expect : will the callback function be called before or after the loop?

The result

I ran the script a lot of times with a lot of numbers and it was always the same thing : the callback function waits for the loop to be over before it is executed. It means that the current function is not paused.

Now it’s your turn

I want you to take a look at the script (complete php code) (I know it’s poorly written, it’s just a test) and tell me if I’m wrong or if I’m right.

Thanks to you all!

Ask Dan : Procedural VS object-oriented in javascript

Since the beginning of Ask Dan a javascript question, I received a bunch of questions. Here’s the first one I received. It’s from Andrew Worcester.

There seems (to me anyway) to be an overuse of the “new” syntax in libraries. If I create an Ajax object is there a functional benefit to using: “new Ajax.Request(options)” verses something like “sendAjaxRequest(options)” It seems to me that by using “new” causes more hassle because you need to be sure the objects are properly disposed of. So is there a performance or functional benefit to this technique?

I had a hard time understanding the question (and I was too ass hole to ask…) so I’ll rephrase it in another way : is there a benefit from using object-oriented techniques VS procedural in javascript?

Procedural in javascript

Though javascript was not a procedural language from the start, it has been overused as such in the beginning (and it’s still is). That may be because people didn’t bother learning javascript and they copy/pasted functions from sites that offers low-quality javascript snippet. All they did was “hacking” the poorly written code to suit their needs. This technique worked for a long time but with the use of ajax and DHTML, it’s nearly impossible to have clean code that is not buggy and dirty.

Object-oriented in javascript

The new statement necessary implies the use of objects in javascript. You can have basic information about object in How to create objects in object-oriented javascript and in with the articles tagged Object-oriented of this site.

The benefit of object-oriented

There is one major benefit about object-oriented that creates a lot of other benefits : the cleanliness of the code. The other benefits from that are : the code is easier to maintain, to modify, to read and to explain.

OO applied

I’ll apply it to an example. I want to alert the sound of cat by ajax.

In a procedural way, you’ll approximatively have

  1. // Global variable
  2. ajaxRequest = null;
  3.  
  4. function sendCatSoundAjaxRequest() {
  5. ajaxRequest = new XMLHttpRequest(); // Create the request in the global var
  6. // … code for request …
  7. }
  8.  
  9. function receiveCatSoundAjaxRequest() {
  10. // The sound is in clear text in the response
  11. alert(ajaxRequest.responseText);
  12. }

The problems? You have a global variable to keep track of the ajax request. Because it could be use by every other functions that need ajax, you can’t make more than one request at a time. Also, there are nothing that binds the two methods together apart their names that are look alike. Now, just think of the code when you have 5 or 6 different type of requests. Your code will look like garbage.

In a object-oriented way, you would all write this ugly code in a separated object. Your main call to see the sound of a cat could be something like

  1. var cat = new Cat();
  2. alert(cat.getSound());

The code from above still exists somewhere but the complexity is now hidden behind the Cat class.

Ajax and javascript don’t use threads

Since ajax, a lot of people are thinking that asynchrone means “in a separated thread”. They are wrong!

Synchronous

The XMLHttpRequest object gives you the option to make a synchronous request to a server with the parameter async set to false. It means that when you call the server, all javascript executions will stop and wait for the server to respond to the request. I never saw it used. In fact it is more confusing that anything else because the page seems frozen and users don’t like frozen things. If you use it, you are not cool!

Asynchronous

Now you are being cool! The asynchronous is used by everyone and it doesn’t freeze the page while the call to the server is done. So, if you have a call that takes 30 seconds before receiving the answer, your users will never know that you’re a bad server-side coder that do not optimize the code he’s writing (I’m just joking).

The misconception of asynchronous

People take for granted that because it’s asynchronous, it’s a thread. They are partially right. There must be a thread created by the browser to keep the javascript running while it makes a request to the server. It’s internal and you don’t have access to that thread. But, the callback function called when the server responds to the ajax request is not in a thread.

I’ll explain clearer. If javascript runs some code that takes 5 seconds to execute and an ajax response arrives at 2 seconds, it will take 3 seconds before it will be executed (before the callback function is called). That’s because javascript itself doesn’t create a thread to execute the ajax response from the server and simply waits that all executions are terminated before starting a new one.

So if you’re running a lot of ajax requests simultaneously, you might get some weird behavior because they will all wait one on another before executing themselves.

#UPDATE 2007-06-12
Following one of my readers comment (BK), I have written a sequel to this article : Ajax, javascript and threads : the final truth.

Ask Dan a javascript question : first edition

I proudly announce a new attracting feature for javascriptkata.com : Ask Dan a javascript question. What is Ask Dan a javascript question? Ask Dan a javascript question is the new attracting feature of javascriptkata.com. Readers (you) ask Dan (me) a javascript question and that will be answered on javascriptkata.com. There’s more! When asking Dan a javascript question, you could receive an answer and a link to your site… for free! Isn’t it exciting? And you know what? Ask two questions and receive… not zero… not one… but two answers and links to your site. Isn’t it awesome?

I began by asking some friends to ask Dan (me) a javascript question. Here they are… and you know what? You can read them for free!

PM asked Dan : Does javascript can become a sort of bisexual slave that makes my toasts every morning?
Answer : I’m afraid that the answer is no. Javascript doesn’t offer that kind of feature but maybe you could be interested in How to use JSON.

Emile asked Dan : If a kid wants to begin using javascript, does he need a 10 000$ computer or he can use a metal wire and a battery to create binary?
Answer : You know what? It’s up to you to decide which one suits you best. 10 000$ computer? Fine. Metal wire and battery? Fine too. Isn’t it a perfect world? By the way, maybe you could be interested in How to use JSON.

Now, it’s up to you to Ask Dan a javascript question by sending a mail to dan@javascriptkata.com.

Did I mention that sending an email is… free!

3 reasons why I use jQuery

These days, you can’t write a web application without using one of the billionth javascript library. Two of them stood out of the crowd : prototype and jQuery. I will explain why did I choose jQuery.

Prototype

Prototype is comfortably installed in a lot of developers mind because of two reasons : it was the first widely used and script.aculo.us. Being the first accepted library is a hard thing to do and it will always help them. Scriptaculous (I hate to write it with the dots) had an incredible effect on the popularity of prototype. For the first time, we could do “flash animation” without using flash. This was instant popularity.

jQuery

jQuery is one of the bastard child of prototype. It reuses the $() function but brings it to a level you never could have hope for. In fact, jQuery is almost completly based on the $ sign. Why? Maybe because it’s fast, maybe because it’s trendy. I don’t know. Example, you want to download a JSON from a server, $.getJSON(“http://www.thesite.com/thejson”).

Reason #1 : The selectors

jQuery supports a lot of selectors. And when I say a lot, I really mean a lot. First, there’s CSS selectors. You just have to apply what you know about CSS and you can write many complex selectors.

Second, there’s XPath selectors. When I was young (sic!), I wrote a lot of XSL. And when I say a lot, I really mean a lot. XSL makes an intensive use of that XPath thingy. Because XHTML is basically XML, we could use XPath to easily navigate throught the DOM. The problem was that before jQuery, nothing could do that. Now, we can!

In comparison, prototype just has the $(‘theId’) to select a element. Ouch!

Reason #2 : The Attributes

It’s easy to add/remove attributes to any HTML element. I use it when I create new elements or when I need to add/remove a css class on an element. The interesting thing is that you can chain them and it will work. Example, I want

  1. $("div").attr("title", "This is a div").addClass("newClass");

You can add as many as you want…

Reason #3 : Ajax and JSON

Once again, ajax is now easy as 1,2,3. I wrote an article on JSON and in my mind, there’s no real alternative to JSON. jQuery helps you with it.

  1. $.getJSON("http://www.thesite.com/thejson",
  2.         function(json){
  3.                 alert("I received the json and put it in the json var : " + json.toString());
  4.         }
  5. );

It’s a little more complex with prototype.

How to know if it’s a leap year

It always happens : you have some calculation to do with a date and you forget to calculate those friggin’ leap years. Here’s how to do it cleanly.

The first way

Almost every one use this simple rule : if it’s divisible by 4, it’s a leap year. So the code is

  1. var isLeap = theYear % 4 == 0

Wait a minute, I forgot something! If it’s not divisible by 100 but by 400 it is not a leap year… or maybe divisble by 100 and not by 400…

I can’t remember that! Let’s do it another way.

The one and only way

  1. var isLeap = new Date(theYear,1,29).getDate() == 29;

Nice! That’s something simple that I enjoy. Let’s dissect it.

  1. new Date(theYear, 1, 29)

This line simply create a date object that is initialized with the variable theYear. 1 is the month. As in java, the months are 0 = january and 11 = december (I hate that!). 29 is the last day of february when it’s a leap year.

  1. .getDate()

Returns the date part of a date (sic!). It means that for May 23, 2007, it will return 23.

  1. == 29

That’s the magic part of it. As I said in Mastering the date object in Javascript, there’s a special twist that let you work with dates differently than in most of the languages that I used before. When you initialize a date at the 29th day of february on a non-leap year, it will simply use the date March 1, 2007. So a call to the getDate() function would return 1 and not 29.

How to inherit classes in javascript

First of all, since I made the front page of Ajaxian, a lot of new readers joined in. Welcome to all of you. I would also take a moment to explain that Javascript Kata is a technical blog about javascript and though I will talk here and there about ajax, it is not focused on that subject. It is more about the good javascript techniques that should come along with all the ajax you have to do. I update this site 2 or 3 times a week. Keep reading!

There are hundreds of ways to do inheritance in javascript but a single one is simpler, cleanier and prettier than all the other ones.

Note!
Before reading this article, you should take a look at
How to create objects in object-oriented javascript.

A one-liner

To inherit a class in javascript, it’s a one-liner

  1. TheSubClass.prototype = new TheParentClass();

As simple as that!

Where to write the one-liner

The problem with that one-liner is where should it goes? Once again, the answer is simple : after the constructor of the sub-class. It may look strange but it is extremely effective.

  1. /* The constructor of the Mammal class */
  2. function Mammal() {
  3. }
  4.  
  5. /* The constructor of the Cat class */
  6. function Cat() {
  7. }
  8. // The magic that inherits Cat from Mammal is here!!!!!
  9. Cat.prototype = new Mammal();

Is this true inheritance?

In the hundreds of other ways of inheriting classes in javascript, I think that this is the only one that is a true inheritance. What do I mean by true inheritance? I mean that javascript recognizes it as a sub-class of the class. Check this out!

  1. /* Above code goes here */
  2.  
  3. // Create a cat
  4. var theCat = new Cat();
  5.  
  6. // Check if the cat is an instance of the Cat class
  7. if (theCat instanceof Cat) {
  8.     alert("theCat is an instance of the Cat class");
  9. }
  10.  
  11. // Check if the cat is an instance of the Mammal class
  12. if (theCat instanceof Mammal) {
  13.     alert("theCat is an instance of the Mammal class");
  14. }

If you execute this code, you’ll see that the cat is an instance of the Cat class and the Mammal class.

Do not use the alert function in javascript

Picture yourself on a beautiful beach on a warm day. The sounds of the waves is music to your hears. You’re on a comfortable chair with a laptop on your knees connected via an incredible WiFi. You’re using a brand new web2.0 application that must be the gratest web site on the web. Then, you see an infamous alert from javascript…

Back to reality

This alert box from javascript brought you back to reality. You’re in your shitty room, alone. The smell is disgusting. Everything is dirty. All because a developer has used the alert function to tell you something in an application. Don’t let this happen on your web application. Never, ever, ever use an alert box.

History of the alert

The alert was invented in the web1.0 era when it was the only way of showing a dynamic message to a user. That was the time when people loved win32 applications because they were so easy to use (compared to a web application). To have a little bit of win32 in their web world, they (some bad people) created a monster : the alert function that shows a win32 window.

It was it a big mistake because lazy developers still use it because it is so easy. Don’t fall in the trap. Do not use the alert function.

The problem with alert

The user have to click on the message before he can do anything else on the page. Users hate to click. Don’t make them click and show an unobtrusive message that the user doesn’t have to click to continue.

What should I use instead of alert?

Anything else. This includes (but is not limited to)

Light boxes
I personnally don’t like light boxes but they have the momentum at this moment. There are hundreds of library that can help you with them so don’t implement another one and re-use an existing one please…

Contextual messages
Why not show a message where it happened. A little knowledge of DHTML and you’re ready.

Example. On Ecstatik! (a project on which I worked), when there’s an error with the ajax vote, the label “I laughed!” is changed to “error!” written in red. Maybe it’s not the idea of the century but it works and it tells you where the error is.

Fading in/out messages
These ones are more difficult to do but Google and WordPress do it elegantly. Use a library with a fading in/out function and show a message at the top of the page (or anywhere visible by the user). The user will get used to see messages at this place and will like the fact that they don’t have to click.

Note
I expect a lot of people to tell me that I use them in almost all my examples. These are examples and I don’t want to begin to write DHTML just to show the result of bunch of javascript lines.

How to use the self with object-oriented javascript and closures

When I began with object-oriented javascript, I always saw a self here and there without fully understanding what it meant.

Self?

When you see self in some object-oriented javascript, it’s just mean that the developer is using a closure that will reference the current object via a variable named self. Because self is a variable, it could be named anything else. The use of “self” as a name is a unwritten convention but it could be whatever you want.

  1. // Create a cat
  2. function Cat() {
  3.     this.theCatName = "Mistigri";
  4. }
  5.  
  6. // The cat will meow later
  7. Cat.prototype.meowLater = function() {
  8.     // I create the variable self that refers to the this (the current object)
  9.     var self = this;
  10.  
  11.     // I create a timeout that calls the self.meow function within an anonymous function
  12.     /*** NOTE : You don’t always have to create an anonymous function it’s just that in
  13.         this case, it is required ***/
  14.     window.setTimeout(
  15.         function() {
  16.             self.meow();
  17.         }
  18.         , 1000);
  19. }
  1. // The cat meows
  2. Cat.prototype.meow = function() {
  3.     // I can use the this expression!!!
  4.     alert(this.theCatName + " : meow!");
  5. }
  6.  
  7. // I crate an object and call the meowLater() function
  8. var theCat = new Cat();
  9. theCat.meowLater();

Why not use the this?

Because when using closures within an object, the this in the called function (in the above example, in the meow() function) is the window object.

Our last project : Ecstatik!

Frank (of Ruby Fleebie) and I have been busy lately. We worked together on a project called Ecstatik!

What is Ecstatik!?

Ecstatik! is a project that caused Frank and I to be busy lately. But it’s not just that.

Ecstatik! is a digg-like for funny stuff. No more than that. We didn’t want to make the world a better place, we wanted to have a common project and get it done. A project that would break the classic cycle of “I have a project and it will be big” and ends up in a black-hole somewhere in the universe.

For the moment, there’s no fancy features. Not even a good looking design. These things will come one day but the main idea is keep it simple, stupid. This is an overheard expression but an underused one. I think that this time, we’ve done it.

How is it done?

Ecstatik! is all Rails. It was my first time and I rediscovered how pleasant could be the server-side development. I worked with PHP a lot recently and was bored of it. It is so redundant. Create an object. Write a form to create/edit the object. Write SQL to handle this object. Write some more SQL to work with objects that are linked. I hate that! Rails does all that redundant work for you and if you want, you can modify or optimize it without being restricted. This is the way life for a developer should be.

Don’t hesitate and go for Rails!

The javascript side

I didn’t write a lot of javascript because I wanted learn as much as possible about rails. For the voting process, I used ajax/json via JQuery. This javascript library is simply amazing.

  • The selectors combine javascript, css and xpath. It is the most complete HTML object selection ever seen by human.
  • The manipulation of HTML object are easily modifiable.
  • The ajax support offers all we could want of ajax.

Take a look at ecstatik! and have fun!