JavaScript Functions are Weird, Too

Remember when I said that JavaScript arrays are weird because they are also objects? Aside from their numbered elements, they can have, in addition, hash elements (a key and a value).

Believe it or not, functions in JavaScript are just as weird. They also are objects. If you have a function named bar, it can have a property named foo.

Doesn’t seem very useful, does it? After all, functions can already have variables declared inside them.

The difference? These special function elements persist from one call of the function to the next. You can use them to replace global variables that might otherwise cause unsightly clutter.

For instance, if you want a function to keep track of how many times it’s been called, this does the trick:

function add(a,b) {
  if (add.called===undefined) {
    add.called=0;
  }
  add.called++;
  return a+b;
}

or, more tersely but confusingly,

function add(a,b) {
  add.called=add.called+1 || 1;
  return a+b;
}

You don’t have to call the function by its name when you’re in the function, you can use arguments.callee instead.

How about a real world example. [Warning: You probably won’t get your money’s worth unless you compare the before-and-after code. I suggest copying and pasting them into a diff program so you can see the changes highlighted. Or you could just print out this whole blog post and take it to the bathroom.]

Alert! Unresponsive Script!

Sometimes, you might have some code that takes so long to execute that the browser alerts the user that a script has become unresponsive. That tends to take a long time for new browsers (they assume you might be running a Rich Internet Application and that such messages may be worse than the trouble they’re trying to solve), but for old browsers (like my nemesis IE6), the time is short. Something like 3 seconds.

Yummy Morsels

To solve this problem we have to break up work into bite-sized pieces.

Here’s our before case, the brute force (slow) solution to finding prime numbers. Adapted from a C version here.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
    <title><!-- Insert your title here --></title>
    <script type="text/javascript">
        function findPrimes(topCandidate) {
            var primes=[];

            candidate = 2;
            while (candidate <= topCandidate) {
                trialDivisor = 2;
                       prime = true;
                while (trialDivisor * trialDivisor <= candidate) {
                    if (candidate % trialDivisor === 0) {
                        prime = false;
                        break;
                    }
                    trialDivisor++;
                }
                if (prime) {
                    primes.push(candidate);
                }
                candidate++;
            }
            return primes.length;
        }
    </script>
</head>
<body>
    <!-- Insert your content here -->
    <form action="">
        <input type="button"
               onclick='alert(findPrimes(100000))'
               value="Find Primes" />
    </form>
</body>
</html>

Now here’s the version where we only let 1000 numbers be checked at once. After 1000 have been done, we fall out of the code, but before we go we trigger a setTimeout with a delay time of 0. That’s all we need to do to let the browser catch its breath.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
<title><!-- Insert your title here --></title>
<script type="text/javascript">
    function findPrimes2(topCandidate) {
        var persist=arguments.callee;
        var tries=0;
        if (persist.candidate===undefined) {
            persist.candidate=2;
            persist.primes=[];
            persist.topCandidate=topCandidate;
        }
        keepTrying = true;
        while (persist.candidate <= persist.topCandidate && keepTrying) {
            trialDivisor = 2;
            prime = true;
            while (trialDivisor * trialDivisor <= persist.candidate) {
                if (persist.candidate % trialDivisor === 0) {
                    prime = false;
                    break;
                }
                trialDivisor++;
            }
            if (prime) {
                persist.primes.push(persist.candidate);
            }
            persist.candidate++;
            tries++;
            if (tries>1000) {
                keepTrying=false;
            }
        }
        if (keepTrying) {
            persist.candidate=undefined;
            alert(persist.primes.length);
        } else {
            setTimeout(persist,0);
        }
    }
    </script>
</head>
<body>
    <!-- Insert your content here -->
    <form action="">
        <input type="button"
               onclick='findPrimes2(100000)'
               value="Find Primes" />
    </form>
</body>
</html>

Compare the two versions. In the second, I’ve short-circuited the loop so that it only checks 1000 numbers to see if they are prime. To keep comparisons easy, I’ve tried to make the least number of changes I could. In real-world cases, you start with the idea that you’re going to work in chunks, and your code ends up cleaner.

Some Are Sticky, Some Aren’t

We’ve made some of the variables persistent. These are the ones that have to be kept across invocations of the function. All other variables dry up and blow away.

Since arguments.callee is such a long name, I’ve set the variable persist to hold the current function name.

This is not a recursive function. We let the function finish. It’s set up to be called again with setTimeout. You don’t want to wait around in busy loops, making the browser all gummy and unresponsive.

If you do have responsiveness problems, put a longer delay and check fewer candidates at a time. This will make the process take longer, of course. It’s a trade-off.

Any wait longer than a couple seconds is going to make the user wonder what’s going on. A progress bar is the best solution for long waits. For short waits, a throbberis OK.

Program flow is not obvious when using setTimeout to control flow. In larger programs when you’re using this technique, you may want some kind of handler that’s in charge of passing control from one section of the code to another, instead of hardcoded setTimeout chaining.

About these ads

2 Comments

  1. August 27, 2008 at 4:15 pm

    twrcpv qxzosy etvhskui hwrmxgqz qlcj lfikv tbnziuhrl

  2. Nosredna said,

    August 27, 2008 at 4:41 pm

    Could you elaborate?


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: