I have written a C function that I am able to execute from Angular/TypeScript/JavaScript using WebAssembly:
testWebAssembly() {
Module.ccall("aCFunction", null, [], []); // takes a few seconds to finish
}
This function does some heavy mathematical calculations and needs a few seconds to finish. It is fired when a user clicks a button:
<button (click)="testWebAssembly()">Launch C function</button>
Is it possible to execute the function so that it does not block the UI of the web application?
I tried setTimeOut
/async
/Promise
, but I don't seem to be able to make it work.
Thank you!
The I/O APIs on the web are asynchronous, but they're synchronous in most system languages. When compiling code to WebAssembly, you need to bridge one kind of APIs to another—and this bridge is Asyncify. In this post, you'll learn when and how to use Asyncify and how it works under the hood.
WebAssembly is a low-level assembly-like language with a compact binary format that runs with near-native performance and provides languages with low-level memory models such as C++ and Rust with a compilation target so that they can run on the web.
Unlike Javascript, WASM is statically typed, which means code optimization occurs far earlier in the compilation process before the code reaches the browser. Its binary files are considerably smaller than JavaScript's, resulting in significantly faster loading times.
To use WebAssembly in JavaScript, you first need to pull your module into memory before compilation/instantiation. This article provides a reference for the different mechanisms that can be used to fetch WebAssembly bytecode, as well as how to compile/instantiate then run it.
Asynchronous execution alone won't take it off the main thread. What you actually mean is executing it concurrently. The only way to achieve that on the Web is by using worker threads.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With