Sometimes a little sleep is ok
Thread.sleep() has always been considered a “bad thing” in programming, something you do when you don’t have a good alternative. You could sleep() when you’re polling for a long operation, but the better solution would always be to get a notification when the operation completes, to avoid blocking a thread and generally wasting time – if the operation finished in 600 milliseconds, and you poll only every second, then you completely wasted 400 milliseconds, right?
Well, it turns out there is at least one use case where you really should waste those extra 400 milliseconds – User Interface.
I recently implemented a web UI component that checks if another website is reachable, and only then proceeds. If the website is not reachable, the user has to stay on that page and try again (perhaps he mistyped the URL). I implemented a server method that checks if the URL is alive, and called it from the client side via AJAX. The code looks something like this:
showLoadingIcon(); // displays a "loading" GIF $.post(url, function(result) { hideLoadingIcon(); if (result.good) { // proceed } else { // Display error message } }); |
Well, it turns out that while this code is perfectly correct and efficient, it feels erratic from a usability perspective. If the page took a long time to access, it would behave fine, but if the page was very quick, and the method returned within say 200 milliseconds, the “loading” icon would flicker, creating an annoying experience for the user.
The solution is adding a manual, “artificial” sleep(). If the loading was long, no sleep was necessary, but if it was too short, I added a call to setTimeout, to ensure the loading image is always spinning for at least a full second.
While this is not really an example of Thread.sleep() (that doesn’t really have a javascript equivalent), this does show that sometimes delaying an interaction is required to reduce the user’s pain or confusion.