Hey everyone! I'm thinking about building a small programming language with an interpreter in JavaScript that would run in web browsers. I'm trying to figure out the best way to execute a program with this interpreter. Here's where I'm at:
1. The interpreter should have a `interpreter.run()` method with a loop to run programs until they're done.
2. One issue I face is that running this directly in JavaScript would block the main thread and freeze the UI. To avoid that, I'd need to implement incremental execution using `setTimeout(interpreter.keepRunning())`.
3. Since `setTimeout()` has a minimum timeout of about 4 ms, that would limit the execution to roughly 250 instructions per second. I wonder if instead of that, I could stop every n instructions to set up the `setTimeout()`, similar to a "fuel" approach I read about in a blog on stackless Lua interpreters.
4. Some instructions might depend on specific events (like the end of an animation), so I'd need to set up event listeners rather than just relying on `setTimeout()`.
Is my reasoning sound on this? Can I improve this approach using async/await, generators, or promises? I'm not super well-versed in JavaScript concurrency, so any corrections or advice would be appreciated!
As a bonus: Would this method be portable to other JavaScript-based platforms like Node.js or GNOME JS?
Thanks a lot!
**EDIT**: Just to clarify, I'm concerned that using Web Workers might introduce communication overhead that isn't worth it since my language would primarily interact with other JS functions.
2 Answers
If you're considering performance, checking out WebAssembly could be a good move. It allows you to compile to a performant binary format that runs closer to native speed in the browser. You could have your compiler output to wasm instead of JavaScript! That could boost execution speed significantly.
In your case, using workers might really help. You could transform your language's source code into equivalent JavaScript code and then use a Function constructor to run it. This way, you keep the UI responsive while your interpreter does its thing!
Related Questions
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically
[Centos] Delete All Files And Folders That Contain a String