Archive for the ‘black belt’ Category.

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.

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!

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!

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.

How to do a non-destructive overwrite of a function in javascript

I really don’t like the “non-destructive” expression but I couldn’t come up with a better one.

What?

You want to create a function but you will overwrite the old one. You just want to add some code before or after it.

Example, you create a javascript applet that can be added to web sites you do not own and you want to call a function in the body.onclick() event. Maybe the site already has something in the body.onclick() event and you don’t want to overwrite it because the other developer will be mad at you. You’re stuck!

How?

First of all, don’t panic. Take a deep breath and relax.

Now, you’re ready.

  1. var oldBodyOnClick = body.onclick;
  2. body.onclick = function() {
  3.         // Add your code here!
  4.         alert("Before the old event");
  5.  
  6.         if (oldBodyOnClick != null) {
  7.                 oldBodyOnClick();
  8.         }
  9.  
  10.         // or here!
  11.         alert("After the old event");
  12. }

Could you repeat slower please?

Ok.

First, I assign the body.onclick() event to a new variable.

  1. var oldBodyOnClick = body.onclick;

Second, I create a new function that will be called on the body.onclick() event.

  1. body.onclick = function() {

Third, I add code before the old event

  1. alert("Before the old event");

Fourth, I call the old event if it is not null

  1. if (oldBodyOnClick != null) {
  2. oldBodyOnClick();
  3. }

Third, I add code after the old event

  1. alert("After the old event");

That’s it!

The problem with bookmarklet

I talked earlier about bookmarklets and how wonderful they are. In today’s web2.0 world, you can’t have a successful application without giving your users a cool bookmarklet. It can be easy to do sometimes (like the one of del.icio.us) but you always want to do more and it gets more complex… until the day you hit the wall

The problem

You can’t execute code without a click of the user. It is obvious to 99,42% of you, but there will be a day when you’ll just say “I want to execute some friggin’ code without a click from the user”. Even if you want to do it to simplify the life of the user, you can’t. There must be a solution.

The solution

For now, the solution is called GreaseMonkey. This is a Firefox add-on that executes javascript automatically when certain pages are called.

Example, I want every background color of every web page I visit to be gray. I would create a script with this code


document.body.style.backgroundColor = "gray";

and it would just work.

The problems of the solution

It is Firefox only. With around 75% market shares, Internet Explorer just can’t be forgotten.

It is too complex
. The user has to know how to install add-ons and how to install greasemonkey scripts. It is way to hard for a normal user.

The real solution

I don’t have one and that’s why guys that I ask you : how to execute javascript code automatically without a click from the user?

I want all the solutions you can give to me wether it is real or fantasy.

Thanks alot!

How to do a bookmarklet with javascript

The day I discovered it, I was really happy. Not happy as a fish in water but maybe happy as a cat having its meal (though it enormously depends of which cat we are talking about). Talking about bookmarklet to some of my friends, I saw that there were a lot of incomprehension about it. So I’ll begin at the beginning.

What is a bookmarklet?

A bookmarklet is a chunk of javascript code that can be added as a bookmark in your browser. When you click the bookmark, the javascript is executed. This can do a lot of things.

To add a bookmarklet, simply drag the link into your bookmark toolbar.

Why does it work?

It works because when a page is loaded in the browser (the client), it has complete power over it. Using javascript, you can do whatever you want without being stopped by some kind of security. Isn’t it wonderful?

How to do a bookmarklet

1. Write some javascript that does something useful
2. Put it in a link with the command javascript: before it and void(0); (just to be safe) after it
3. Tell the people to drag the link in their bookmark toolbar

I have to say that the javascript code has to be less than 2083 characters, the limit of characters that enters in the address bar in Internet Explorer.

How to import another JS in a bookmarklet

You want to have a complex “application” executed on a page but you can’t do it in less than 2083 characters? As I said earlier, the client has the complete power over the currently displayed page so you can import javascript files in the current page.


var script = document.createElement("script");
script.src="http://www.example.com/javascript.js";
document.body.appendChild(script);

Now, put that on one line add javascript: at the beginning and void(0); at the end and you’re set.

Now, let your creativity flow and make a great application.

A common problem with the powerful javascript closures

I recently wrote about closures and how easier your javascript will be to maintain and how good it will look. Now is the time for me to be a Closure-Grinch.

Closures keep a reference to a variable, not a copy

[source:javascript]
// Create a Buy Viagra function
function buyViagra() {
var pills = 2;

// Create a closure to alert the number of pills
function alertPills() {
alert(“Number of pills : ” + pills);
}

alertPills();

// Increment the number of pills
pills += 1;

alertPills();
}

buyViagra();
[/source]

Looking at this code, it can be pretty obvious that the alert containing the number of pills will be “2″ the first time and “3″ the second time. That’s because the closures contains the reference to the variable and not a copy.

The common problem with closures and loop

That’s a more common problem. We use closures in a loop (for or while) and it always keep the last value of the increment.

[source:javascript]
// Functions that will alert a number
var alertFunctions = new Array();

for (var iNumber = 0; iNumber < 3; iNumber++) {
function alertFunction() {
// We use the closures to have access to the variable “iNumber” (from the loop)
alert(“Number is ” + iNumber);
}

alertFunctions.push(alertFunction);
}

// We loop and call each functions
for (var i = 0; i < alertFunctions.length; i++) {
alertFunctions[i](); // Call the function
}
[/source]

We would expect that three alerts pop having 0, 1, 2. But instead, it alert 3, 3, 3. This is because the iNumber variable was 3 when it got out of the loop.

How to solve the problem

[source:javascript]
// Functions that will alert a number
var alertFunctions = new Array();

for (var iNumber = 0; iNumber < 3; iNumber++) {
// Magic here!
var alertFunction = function(x) {
return function() { alert(x); };
}(iNumber);

alertFunctions.push(alertFunction);
}

// We loop and call each functions
for (var i = 0; i < alertFunctions.length; i++) {
alertFunctions[i](); // Call the function
}
[/source]

Step #1
var alertFunction = function(x) {

I create a new function that will take a parameter. The parameter will contain a copy of the variable I send to it.

Step #2
return function() { alert(x); };

I return a function that will alert the copied parameter of step #1.

Step #3
}(iNumber);

I call the newly created function (that returns a function).

The power of closures in javascript

Now is the time. I can’t go forward if I don’t talk about closures. What are closures? Closures are your friend. That’s the first thing you need to know about them. They will help you keep your code clean, healthy and easy.

A closures is created every time you create a function in a function (they are also created in other situations too but I won’t talk about them now). When using a closure, you will have access to all the variables defined in the parent function (and all its parent functions too).

Attention! Before reading this article, you should take a look at 3 ways of creating functions in javascript.

Write your first closure

  1. function function1() {
  2.         var var1 = 1;
  3.  
  4.         // Magic here! I create a function inside another function
  5.         function function2() {
  6.                 var var2 = 2;
  7.  
  8.                 // I have access to var1 defined in function1
  9.                 //(the parent function of the current one)
  10.                 alert(var1 + var2);
  11.         }
  12.  
  13.         // Call function2
  14.         function2();
  15. }
  16.  
  17. // Call function1 (should alert 3)
  18. function1();
  19.  

For the moment, it doesn’t make sense but you will surely find a handy way of using it.

Example of a closure

Example of a closure, I want to alert the ID of the timer (returned by window.setTimeout) after 1 second.

In an old-fashioned (without closures) way, I would do the following.

  1. var globalTimer = null;
  2.  
  3. function createTimer() {
  4.         // I create the global timer
  5.         globalTimer = window.setTimeout(alertTimerId, 1000);
  6. }
  7.  
  8. function alertTimerId() {
  9.         // Alert the global timer ID
  10.         alert("The timer ID is " + globalTimer);
  11. }
  12.  
  13. createTimer();
  14.  

There are many problems with that code. The most obvious one is : it uses a global variable. You never know what happens to global variables between the time it is instantiated and the time it is used. It’s bad.

In a new-fashioned (with closures) way, you would do this.

  1. function createTimer() {
  2.         // I create an inner-function that alerts the timer ID
  3.         function alertTimerId() {
  4.                 // I call the "timer" variable from the parent function (using closures)
  5.                 alert("The timer ID is " + innerTimer);
  6.         }
  7.  
  8.         // I create the timer
  9.         var innerTimer = window.setTimeout(alertTimerId, 1000);
  10. }
  11.  
  12. createTimer();

I have solved the global variable problem.

Now, what can I do?

Because closures are not implemented in every programming language (update : though it is not specific to javascript), you’ll have to try it for yourself. I don’t want to give you recipes on how/when to use it, it’s up to you. But I could say that a great ajax web2.0 application normally uses a lot of closures.

Keep in mind that
- Closures are created everytime you create a function in a function
- Closures give you access to variables that are defined in the parent function (and all of its parents)
- A closure keeps a reference to an object, not a copy (more on that later)
- Watch out for memory leaks in Internet Explorer!!!

3 things that javascript and Ruby have in common

When I decided to start Javascript Kata, a friend of mine just thought it was a cool idea and started his own site, Ruby Fleebie. I’ve never written code in Ruby but it looks like a very pleasant language. He borrowed me Agile Web Development with Rails: A Pragmatic Guide and I really liked the look of the code (by the way Frank, I’ll give it back to you soon, promise). But as I am reading Ruby Fleebie, I always see similarities with javascript.

A great knowledge of javascript won’t get you a job. But knowing a “serious” language + great knowledge of javascript and you will be rich (… but maybe not). So, why not take Ruby as the “serious” language as it is the rising star these days?

So here’s a first draft of the list of similarities.

1. Everyone can modify your class structure

A lot of “serious” developers think about this as a weakness but this is the greatest thing that happened to languages since object-oriented. No more protecting you from yourself. Just that great feeling of liberty (you know the one when you are on the deck of a boat by a starry night with Leonardo DiCaprio behind you).

Ruby : 3 steps to understand how classes and objects work in ruby
Javascript : What are javascript prototypes? (short answer for advanced javascripters)

2. You can pass a function as a parameter

In javascript, any function can be passed as a parameter.

[source:javascript]
// Create a function that alerts a number
function showNumber(theNumber) {
alert(theNumber);
}

// Create a function that “shows” 42 using
// It takes as parameter the function that will show the number
function show42(theShowNumberFunction) {
theShowNumberFunction(42);
}

// Call to show 42
show42(showNumber);
[/source]

In ruby, it is called code blocks.

[source:ruby]
// Create a function that alerts a number
def show_number(theNumber)
puts theNumber
end

// Create a function that “shows” 42 using
def show_42()
yield(42)
end

def main
show_42() do | theNumber |
show_number(theNumber)
end
end

[/source]

Ruby : An introduction to code blocks
Javascript : 3 ways of creating functions in javascript

3. Walk like a duck?

You want an object to do something (walk like a duck) but you don’t know the type of object and you don’t know if it can.

In javascript, no problem, you just check if the object has the function (now that we know that objects are javascript objects are hash-tables)

[source:javascript]
// Create a Dog class without functions
function Dog() {
}

// Create a Cat class with a walkLikeADuck function
function Cat() {
}

Cat.prototype.walkLikeADuck = function() {
// Code to walk like a duck
}

var theDog = new Dog();
var theCat = new Cat();

// Check if they can walk like a duck
// by using [theObject].[thePropertyOrMethod]
alert(“The dog can walk like a duck? ” + (theDog.walkLikeADuck != null));
alert(“The cat can walk like a duck? ” + (theCat.walkLikeADuck != null));
[/source]

In Ruby, it is simple too! Just use the respond_to method.

[source:ruby]
#… code for creating classes …

# Check if they can walk like a duck
puts “The dog can walk like a duck? ” + (theDog.respond_to?(:walkLikeADuck).to_s)
puts “The cat can walk like a duck? ” + (theCat.respond_to?(:walkLikeADuck).to_s)
[/source]

You’ll see that only the cat can walk like a duck.

Ruby : What’s the fuzz about ducktyping?
Javascript : How to use javascript hashes (or hash-table)