7 ms·
It's trivial to periodically pass control back to the UI with setTimeout or setInterval. So doing something that takes 8s doesn't have to block the UI at all.
by eueueu 11y ago
It's trivial to periodically pass control back to the UI with setTimeout or setInterval.
So doing something that takes 8s doesn't have to block the UI at all. The "without webworkers" version should be renamed to "Naively programmed version" or something.
- tedunangst 11y agoDoes that work?
- eueueu 11y agoYes it does. I'm not convinced multithreading is something that should be encouraged within javascript personally.
- magicalist 11y agoIt gets ugly fast. Most tasks are not a simple sort. There's a reason that cooperative multitasking is not widely used in operating systems anymore.
- eueueu 11y agoJavascript is not an operating system. There aren't many operations in javascript which will block. The only real issue is that your javascript code executes in the same thread as UI. Which just means you need to think a bit harder about keeping it responsive. "Start threads!" in programming is usually a lazy hack.
- LnxPrgr3 11y agoLazy hack, or using OS/browser/whatever features instead of reinventing them poorly? What's the benefit you get from programming like that?
- eueueu 11y agoBecause once you introduce threads, your program complexity increases massively. You're now throwing a few groups of instructions at the CPU and saying "Hay! Execute these instructions in any order you like". Then you're adding code to deal with the issues of that random execution entails. Also, it's not faster, so what's the actual point? The browser should use all CPU cores efficiently to make javascript fast. Exposing WebWorkers to javascript programmers IMHO is totally the wrong way to do that.
- onion2k 11y agoIn the case of something as simple as a bubble sort, you probably could code something to periodically hand control back to the browser to pick up input events, but I imagine that would slow it down considerably as you'd need to check every few milliseconds otherwise the user will see some lag. Also, in something more complex inserting breaks would be a lot harder. Why bother when web workers are a good, working solution?
- eueueu 11y agoI'd bet using setTimeout with a 0ms delay every loop wouldn't slow the example down significantly, and would have the desired effect of making the UI responsive.
- wging 11y agoYou might be surprised. There are conditions under which browsers will impose a 4ms minimum delay when you ask for less. I believe it's when you set a timeout within a timeout. Edit: close. https://html.spec.whatwg.org/multipage/webappapis.html#timers https://html.spec.whatwg.org/multipage/webappapis.html#timer... "Timers can be nested; after five such nested timers, however, the interval is forced to be at least four milliseconds."