Tales from the Evil Empire

Bertrand Le Roy's blog


Bertrand Le Roy

BoudinFatal's Gamercard

Tales from the Evil Empire - Blogged

Blogs I read

My other stuff


May 2009 - Posts

Survey: Ajax usage among .NET developers

(c) Bertrand Le Roy 2003 If you haven’t already and you are a .NET developer, please take a couple minutes and answer this survey, whether you use Ajax or not. There are a number of Ajax surveys around, but Simone’s is the only one that focuses on .NET developers.

The survey:

Simone’s post:

Twitter contest: what can you code in 130 characters?

I just posted the following snippet on Twitter. The exercise is to write meaningful and preferably cool code that fits in a Twitter message along with the #twitcode keyword, which leaves 130 characters.

private static readonly byte[] _blankGif =

I can’t wait to see what people come up with.

Monitor the results from here:

setInterval is (moderately) evil

bleroy05 JavaScript has two ways of delaying execution of code: setInterval and setTimeout. Both take a function or a string as the first parameter, and a number of milliseconds as the second parameter. The only difference is that the code provided to setInterval will run every n milliseconds whereas the code in setTimeout will run only once.

Before I explain why I think setInterval is evil, allow me to rant on a related subject for a paragraph: you should never pass a string into any of those functions and instead always pass a function reference (unless you really, really know what you’re doing). If you pass a string, it will have to be evaluated on the fly, and eval is quite evil itself (unless you really, really know what you’re doing). It might seem tempting to generate code this way to inject dynamic parameters, but there are better ways of doing that, using currying. In Microsoft Ajax, for example, we provide the handy Function.createCallback and Function.createDelegate for exactly that usage.

Anyways now let’s get back to the issue at hand: setInterval is evil. To better compare, let’s assume you have a reason to use setInterval (why else would you be reading this?). Here’s the code you might write:

<!DOCTYPE html>
    <script type="text/javascript">
        var interval = setInterval(appendDateToBody, 5000);

appendDateToBody() { document.body.appendChild( document.createTextNode(new Date() + " ")); } function stopInterval() { clearInterval(interval); } </script> </head> <body> <input type="button" value="Stop" onclick="stopInterval();" /> </body> </html>

Both APIs have a corresponding clear API that enables the developer to cancel the interval or timeout. To identify what interval or timeout you’re cancelling, you pass into the API a token that is whatever value the call to setInterval or setTimeout returned. And that’s a first reason why setInterval is (mildly) evil: if you lose that token, there is no way you can ever stop that code from running every five seconds until you navigate away from the page. But that is a minor inconvenience, it just means you need to carefully manage your own stuff, right? Well, actually if code that you don’t know or don’t control created that interval, you’re probably in trouble even if you kept your own house real nice and tidy…

But the real reason why I dislike setInterval is that it is quite hard to debug, in particular if you have more than one running simultaneously. For example, if you have two intervals, one running every 100 milliseconds, the other every five seconds, and if you want to debug the second one, the first one will constantly get triggered and will get in the way.

So what, you might say, is the alternative? Well, here is code that is quasi-equivalent to the code above, but that uses the much less evil setTimeout:

var interval = setTimeout(appendDateToBody, 5000);

function appendDateToBody() {
        document.createTextNode(new Date() + " "));
    interval = setTimeout(appendDateToBody, 5000);

function stopInterval() {

Here, instead of taking a subscription for life, we’re just renewing the lease as we go. The big advantage of this code is that to stop the interval, you don’t need the token. Actually, I rarely even bother to keep hold of it. All you have to do is skip the line of code that renews the timeout for the next iteration. So no housekeeping to do, and if during a debugging session you need to get one of the interval functions out of the way, just drag your debugger’s current execution pointer to the end of the function, hit F5 and you’ll never see that function run ever again, boom, it’s out of the way and you can focus on your own debugging.

So to summarize, replacing setInterval with setTimeout is easy, pain-free and removes the inconveniences of setInterval. So while the setInterval evil is about at the level of not replacing the cap of the toothpaste, the non-evil alternative is so easy that I can’t see a reason not to forget about setInterval for good.

New release of the Ajax Control Toolkit

A new version of the AJAX Control Toolkit is now available for download from the CodePlex website. It contains three new controls:

HtmlEditor HTMLEditor - allows you to easily create and edit HTML content. You can edit in WYSIWYG mode or in HTML source mode. The control exists as a server-side extender but can also be instantiated purely on the client-side with a single line of code. Many thanks to Obout for building this.

ComboBox ComboBox - provides a DropDownList of items, combined with TextBox. Different modes determine the interplay between the text entry and the list of items. this control behaves very much like a Windows combo. Many thanks to Dan Ludwig for building this.

ColorPicker ColorPicker - can be attached to any ASP.NET TextBox control to provide client-side color-picking functionality from a popup. Many thanks to Alexander Turlov for building this.

The ASP.NET website has been updated with new videos and tutorials for these controls.

This new release also includes fixes for over 20 of the most voted bugs in existing AJAX Control Toolkit controls and now features minimized release versions of the script files.

The release can be downloaded as a server dll or as a set of files for use with pure client-side applications.


Creating jQuery plug-ins from MicrosoftAjax components

(c) Bertrand Le Roy We had an interesting discussion recently on the ASP Insiders mailing list and ended up talking about what cool stuff we could build on top of jQuery. Many interesting things were mentioned and it was a very useful discussion but one suggestion in particular struck my curiosity as it was something I had investigated before and that could be improved on with very little code.

I had already written a little plugin to enable instantiation of Microsoft Ajax components on the results of a jQuery selector:

jQuery.fn.create = function(type, properties) {
    return this.each(function() {
        Sys.Component.create(type, properties, {}, {}, this);

I have another version that is a little more elaborate and takes a bag of properties and events instead of just properties (get it from the attached sample) but you get the idea. This makes it fairly easy to instantiate components based on a selector:

    .create(Bleroy.Sample.CharCount, { maxLength: 5 });

But if this were a native jQuery plugin instead of a Microsoft Ajax component, as Rick Strahl suggested, chances are you’d do something like this instead:

$(":text.nomorethanfive").charCount({ maxLength: 5 });

We can actually get that exact result fairly easily by writing a plugin that is specific to this component, but we can’t expect every Microsoft Ajax component author to also write a jQuery plugin, can we? We can do better than that. Here is a second small piece of code that is still generic but is in the business of creating jQuery plugins:

Sys.Component.exposeTojQuery = function(type, pluginName) {
    return jQuery.fn[pluginName] = function(properties) {
        return this.each(function() {
            Sys.Component.create(type, properties, {}, {}, this);

Like above, the version in the sample is better than that in that it supports events in addition to properties but again you get the idea. Thanks to this function, we can create a jQuery plugin for any existing Microsoft Ajax component with a single line of code:

Sys.Component.exposeTojQuery(Bleroy.Sample.CharCount, "charCount");

After this call, we can write exactly the code we wrote before, but without having had to write a specific plugin. We can then use charCount like a native jQuery plugin:

$(":text.nomorethanfive").charCount({ maxLength: 5 });

This is really easy to use, and I quite like it. We could for example add the following line of code to the new MicrosoftAjaxTemplates.js:

if (jQuery)
Sys.Component.exposeTojQuery(Sys.UI.DataView, "dataView");

This would enable us to instantiate DataView controls as simply as this:

<ul class="dv">
    <li>{{ $dataItem }}</li>
<script type="text/javascript">
    $(".dv").dataView({ data: ["foo", "bar", "baz"] });

Get the code from here (you need to include jquery-1.3.2.js to the script folder):

Five gems of XBLA
  1. The Maw is a charming and seriously fun game that is going to make you smile from start to finish.
  2. Puzzle Quest is one of those “just one more” time sinks. The improbable mix of puzzle gaming and RPG is just awesome. The sequel, Galactrix, is pretty good too (but quite buggy, you might want to wait for a patch or at least regularly copy your game save).
  3. Portal is simply the best game ever, at least for me. Portal proves once more that the simplest ideas can be the deepest and does so with amazing grace and mastery of the art of video games.
  4. Banjo Kazooie and Banjo Tooie were two of the best N64 games, maybe on par with Super Mario but with that unique Rare sense of humour.
  5. Cloning Clyde: smart and funny.

What are your favorite XBLA games?

Posted: May 03 2009, 12:20 AM by Bertrand Le Roy | with 3 comment(s)
Filed under:
More Posts