28 April, 2009

window.alert

One of the problems with the alert() function is the inability to cancel it when placed within loops. You may find this function useful:
"use strict";
var alert = function anon() {
    if (!anon.stop) {
        anon.stop = !confirm(Array.prototype.join.call(arguments, "\n"));
    }
};
These following lines of code are identical:
// Old:
alert("Hi!");
// New:
alert("Hi!");
// Old:
alert(1 + "\n" + 2 + "\n" + 3);
// New:
alert(1, 2, 3);

However, an even more powerful feature of this new alert() function is that if it is called repeatedly, you can click the "Cancel" button to prevent it from displaying any more alerts!

Credit for the idea goes to this blog. The actual code is all by me, though.

[LINK] The unit tests.

No comments:

Post a Comment