Ask Dan : More on javascript threading

From time to time, I receive emails from desperate people who want help with their javascript problem. I also receive a lot of emails of people wanting to help me with my “manly problems”. It’s very nice from them to care about me and I take time to reply to each of them but I don’t have that kind of problem for the moment.

Stuart Cooper recently sent me a mail about threading in javascript and I turn to you, javascripters, to find the a solution for his problem. I sent the code on RefactorMyCode for refactorisation and they will automatically show up in the comments of this post (the site is an idea of Marc-André Cournoyer who is a very active developer from Montreal). Don’t be afraid to think outside the box. The solution may be completly different from what is already written.


I am experience trying to create a “cover page” that runs a ping to remote servers.In my code I am using setInterval() to run repeating pings (artificially quickly at the moment, ie 10 seconds rather than 1 min) and display the results to browser. I have built my own XMLHttpRequest module (mainly as a learning exercise) and I don’t believe it to be the source of my ills. I have read through your article and the behaviour of alert() and confirm() fits exactly with what I am seeing when I run the following code :[snippet]

function startup(){

setInterval(“pinger(‘live’,0)”,10000);
setInterval(“pinger(‘standby’,1)”,10000);
setInterval(“pinger(‘dev’,2)”,10000);
setInterval(“pinger(‘test1′,3)”,10000);
setInterval(“pinger(‘test2′,4)”,10000);
setInterval(“pinger(‘test3′,5)”,10000);
setInterval(“pinger(‘test4′,6)”,10000);

}

function pinger(server,divit){

console=document.getElementById(‘ping_div’ + divit);
console.innerHTML=”;
sendRequest(“../php/ping_sys2.php?target=” + server);

}

[/snippet]

(each server has its own named div to return to)

What I am seeing when I run this is the final pinger response from the callback and nothing else. I since added debugging into my XMLHttpRequest code so that it split out the server response progress.

[snippet]

readyXML=xmlReq.readyState;

[/snippet]

[snippet]

if(readyXML == 3){

data=”Serving …”;

}

if(readyXML == 2){

data=”Sent …”;

}

if(readyXML == 1){

data=”Opening …”;

}

[/snippet]

What I have observed is that when running the setInterval commands as above, all except the final request are “jammed” on readyState = 1 and appropriately responds with “Sending …”

however,

when I do the following (which is messy)

[snippet]

function startup(){

setInterval(“pinger(‘live’,0)”,1000);
alert(“something”);
setInterval(“pinger(‘standby’,1)”,10000);
alert(“something”);
setInterval(“pinger(‘dev’,2)”,10000);
alert(“something”);
setInterval(“pinger(‘test1′,3)”,10000);
alert(“something”);
setInterval(“pinger(‘test2′,4)”,10000);
alert(“something”);
setInterval(“pinger(‘test3′,5)”,10000);
alert(“something”);
setInterval(“pinger(‘test4′,6)”,10000);

}

[/snippet]

Each response is absolutely spot on and will continue to generate pings correctly. So in this case the script alert interrupts are forcing the callback request to trigger, whereas without the alerts its only the last request that triggers a callback. I have also tried using artificial timeout loops instead of alerts (which generate the odd browser “script running slowly” message) but to no avail.

At the moment I am almost resigned to having to create individual events (like rollovers, though I would much prefer the ping initialisation to occur window.onLoad()) that trigger the setInterval() … which also seems to work fine.

I am hoping that you may have come across a way of forcing the XMLHttpRequest to respond without forcing alerts or confirms on the user, in the time since the last update to the article.

A new project – I hate PHP

If you are javascripter, chances are that you must work with some back-end languages like ASP.NET, ColdFusion, Ruby On Rails or PHP. If you work with a back-end language, chances are that you become frustrated against it sometimes. That’s why I created I hate PHP.

What is it?

I hate PHP helps you to evacuate your daily frustrations against the PHP language via Twitter. It’s simple. You must tell your twitter username to I hate PHP (on the website) and then, send a direct message to the ihatephp twitter user in the following format : d ihatephp a thing that frustrates you in PHP.

Why against PHP?

I could have done it against a lot of languages because they all suck in their own special way. But the moment I was thinking about the project, I was working with PHP and I just kept sending IM messages to Frank (of Ruby Fleebie) to tell him about things that frustrated me in PHP. I just made it more “official” and now I tell it to the world via I hate PHP.

Subscribe to the RSS of I hate PHP!

Barcamp Montreal 3 and this site

Like most of you already knew, I’m working with Frank Lamontagne of Ruby Fleebie on a project called TimmyOnTime. We had the chance to present it at the last Barcamp Montreal and it went… really bad! If you want to know more about the whole adventure (and have a good laugh), click here to read the story written by Frank. (By the way, I used a good ol’ click here link just for the fun of it… I never did it before and frankly, I like it… almost…).

What happens with Javascript Kata?

I know, I have been negligent with site. It’s really shameful to let a great site die and there’s no one to blame but me. Why I did that? I could give hundreds of reasons but they would all be lies. I really don’t know what happened.

I want to give another twist to JavascriptKata. I want to get back to a more tradional reference site because I don’t like the concept of a technical blog after all. I want the articles to be more persistent, not just a post that everyone forget about after a while.

But, there would be a RSS feed too. I would announce new articles on the site. I would also use it to debate on tricky things about javascript and then make an article out of it.

I really would like to hear you about this idea, please comment!

3 reasons why I still love Firebug

There was a buzz around Firebug a couple of months ago. A lot of developers installed it and enjoy every second they use it. There are some others that missed the train and are still using alerts to debug. If you’re from that second category, here’s your chance to get back on tracks.

1. The console

Firebug console

The console is a kind of dashboard. It shows what happens client-side : CSS, javascript error, warnings, ajax… all you want to know in just one sight.

If you have an error, just click on it and Firebug will open the source code and highlight it.

Every ajax request is also shown here along with its parameters and the response from the server.

2 . Debugger

Firebug debugger

The debugger is insanely efficient, it offers everything you would expect from a debugger : breakpoints, step-by-step, watch expressions and functions stack. Do you need anything more?

3. Inspector

Firebug inspector
Great, there’s an alternative to the infamous “View page source and then search through the code” technique. With Firebug, you just click on Inspect and move your cursor over the element that causes the problem and you have it all in one sight : the HTML on left and the CSS style on right. You can manipulate both of them to try to correct the problem and then, it’s done.

Conclusion

There’s no reason in the world why you shouldn’t use Firebug, go and get it at http://getfirebug.com/.

Ask Dan : Friggin’ libraries

I received two questions about librairies in the Ask Dan a javascript question serie. Don’t forget to ask me your questions too by sending a mail at dan@javascriptkata.com.

Effects

Camilou asked

Is it too hard to a poor mortal like me to achieve that fancy effects that some libraries like Prototype do offer? I mean, that drag-and-drop stuff looks pretty complicated to me. Or maybe I am just too noob.

Drag-and-drop is complicated but not that much. Thousands of people have done it before the libraries-era. But, I’d say that if you want to achieve something similar to prototype, you’ll probably work for months. Prototype is the most known javascript library and if you start today, there’s little chance you will get as far as them. Sorry. But if you have a very different and easier way of doing things, maybe you’ll succeed.

Creating a new library

Frank Stepanski asked

If I want to start creating my own JS libraries, how do I start?

If you have no better idea than re-implementing what already exists in other libraries, you’ll never know where to start. A new library should fill a hole that is not filled by anyone else. So, you’ll find where to start the day that you will want to do something and that you won’t find any library that does it.

TimmyOnTime

We are still working on TimmyOnTime. TimmyOnTime is a time-management that uses instant messaging so you don’t forget to track your time. There are still places available for the alpha period. Please, give us some feedback.

A new project : TimmyOnTime

Some of you might know that I have worked with Frank Lamontagne of Ruby Fleebie on a project called Ecstatik!. That was the beginning of something.

Now, we are very pleased to announce you our new project : TimmyOnTime.

What is TimmyOnTime?

TimmyOnTime is a IM-based time management tool. To use it, you only need a Jabber client like Google Talk or Gaim (MSN or AIM users don’t despair! We also added support for these 2 networks). To have Timmy track the time on your projects, you only have to chat with him via your IM! Let’s say for example you want to create the following new project : Achieve hapiness. Well, you just tell Timmy about it and you write : create project achieve hapiness

Timmy will create your project and tell you if everything went OK in the process. Now that you have a project, you might want to create some tasks? Nothing is easier : create task smile more often

At this point, Timmy have started the first session on your new task. To stop the timer, just write : stop

Web access is optional

That’s right. One of the important thing for Frank and me was to make optional the web registration process. So, if you don’t want to bother about the website, just use your IM and chat with Timmy. However, we’re pretty sure you’ll want the added features of a web access (project / task renaming, time editing, etc).

It’s your chance!

We want to offer to RubyFleebie and JavascriptKata readers the chance to try this brand new application first. Since it is an Alpha release, we decided to limit to 150 the number of users that can access TimmyOnTime. If everything goes smoothly, we will increase that number slowly over time.

During this alpha period, we would appreciate that you give us feedback on the application. Also, if you find bugs, it would be nice that you let us know! ( contact@timmyontime.com )

To get you started : TimmyOnTime

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!