Ask HN: What is the name for this pattern?
worker = function () {
doSomeWork();
if (isDone()) finishUp();
else window.setTimeout(worker, 0);
}
The basic idea is to use window.setTimeout to schedule another execution of the worker function at the end of the current command queue. While it's not threaded, per se, if your "doSomeWork" functions are small enough, it may as well be for many applications. It allows you to write recursive operations in Javascript, without throwing the "too much recursion" error when the data gets big. And, while it's generally not as fast as straight iteration, it will avoid the "Script on this page is taking too long" error, and it doesn't lock the browser, so it "feels" faster.For operations that you can expect to be slow, or for doing a lot of different actions on a busy page, this pattern is great.
The only problem is that I don't know what it's called, or if it even has a name. I saw a page by Douglas Crockford calling this "eteration", but I think that also means something else, and it never stuck anyhow. It's sort of like tail recursion, in that it is a sort of recursion that doesn't tie up the call stack, but unlike tail recursion, it doesn't track a return value, and it doesn't block the program while it's running. The closest analogy I can think of is putting sleep(0) in a loop so that the OS can step in.
Does it already have a name? If not, got a suggestion?