Can WebAssembly code be executed asynchronously?

I've created a C function that can be run from Angular/TypeScript/JavaScript using WebAssembly.

testWebAssembly() {
    Module.ccall("aCFunction", null, [], []); // takes a few seconds to finish
}

This particular function involves complex mathematical calculations and may take a couple of seconds to complete. When triggered by a button click event:

<button (click)="testWebAssembly()">Launch C function</button>

Is there a way to execute this function without causing the web application's UI to freeze?

I attempted to use setTimeOut, async, and Promise, but had difficulty getting it to work properly.

Your advice would be greatly appreciated!

Answer №1

When utilizing WebAssembly and JavaScript together, they will share the same execution thread. Essentially, running WebAssembly within JavaScript will cause your JavaScript code to pause, and vice versa. This process is similar to executing any other native APIs provided by the browser from your JavaScript code.

If you want to run your WebAssembly in a WebWorker, you can use postMessage to communicate with your wasm code running in a separate thread. An excellent example of this can be found here, showcasing how to render a fractal using WebWorkers:

https://www.reddit.com/rust/comments/8hdq5r/a_rust_javascript_web_workers_fractal_renderer/

It is anticipated that in the future, WebAssembly will introduce its own threading support:

https://github.com/WebAssembly/threads

Answer №2

Merely relying on asynchronous execution does not automatically remove the process from the main thread. The correct term for this is concurrent execution. In order to achieve concurrency on the Web, it is necessary to utilize worker threads.

Answer №3

By breaking down the task into smaller segments, you can delegate control back to the browser after each segment is completed. To ensure your function progresses seamlessly once the browser finishes its current task, you can utilize async to schedule the next segment before exiting the function.

While I haven't tested this method in Rust personally, it is a common approach used in web development to prevent the interface from appearing unresponsive.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to prevent decreasing the value below zero in ReactJS?

I have created two buttons, one for increasing and another for decreasing a counter value. However, when I click on the minus button, it should not display negative values. But in my case, when I click on the minus button (initially at zero), it shows -1, ...

One more time: Utilizing AJAX to save the outcome in a variable with the help of callback (undefined)

I am facing a common problem and despite my efforts, I cannot seem to resolve it. The code snippet I have provided below is causing me trouble: function get_network_from_database(callback) { $.ajax({ type: "POST", url: "load_network.ph ...

Sending a JavaScript array to an MVC controller in .NET 5.0 via a POST request

Trying to send data from a JavaScript array to an MVC controller. While debugging, I end up in the method public void GetJSArray(List<SelectorModel> selectorModels) However, the selectorModels is currently showing as null. Below is the model being ...

Parsing DOM data from an HTTP request in Node.js

Looking to extract data attributes from an SVG element on github.com/profile_name using a node.js HTTP request, and then parsing it into JSON format. <rect class="day" width="10" height="10" x="-36" y="10" fill="#ebedf0" data-count="0" data-date="2017- ...

Steps to transfer an array from an HTML page to Node.js and subsequently save it in a database

Looking for guidance on how to transfer a JavaScript array using Node.js to MySql. Seeking helpful videos or explanations to clarify the process. Thank you! ...

An unusual error occurred stating that the `forEach` property does not exist on the given type

I am working on a chess game and encountering some Typescript errors that I'm struggling to comprehend. The issue arises in the following class method: clickEvent (e: MouseEvent): void { const coordinates: ClientRect = this.chessBoard.getBounding ...

"Observed Issue: Ionic2 Array Fails to Update in HTML Display

I am struggling with updating an array in Ionic2 and Angular2. I have tried updating it on the front end but it's not working, even though it updates perfectly on the backend (ts) as confirmed by checking the console. I need assistance with this. Her ...

Changing function arguments in TypeScript using the spread operator

Could the Tuple spreading syntax in Typescript be utilized to consolidate these function overloads? The challenge lies in the necessity to refactor the function arguments into new types. type Type = TString | TNumber type TString = { tag: 'string&apos ...

Tips for executing several HTTP requests from an array using RXJS

At the moment, I am working on a synchronization service using Angular. My goal is to make a database request and receive an array of URLs in return. The next step is to process each URL sequentially. Below is the current code: return this.http.get<any ...

Utilizing JMeter's WebDriver Sampler to Upload Firefox Profile

Currently, I am working on creating a JMeter script to measure the UI response time for different events using the WebDriver Sampler plugin. In my application, access to the GUI is restricted to certificate-authentication only. Therefore, my concern is wh ...

Changing the value of a textarea in Angular forms using JavaScript

Having trouble with Angular forms? Try this: document.querySelector(TEXTAREA_SELECTOR).value = "some text" Methods like .title, .name, or .innerText don't seem to work. Consider trying these: document.querySelector(TEXTAREA_SELECTOR).dispa ...

Using Redux with Next.js to implement getStaticPaths

Can someone help me understand how to implement getStaticPaths in conjunction with Redux in Next.js? I'm currently using next-redux-wrapper to manage my content, but I am encountering issues when trying to display the data. Below is a snippet of my ...

Issues with the functionality of the ZeroClipboard Angular plugin

"> I'm fairly new to Angular and currently experimenting with a module called ZeroClipboard. I've made adjustments to my application in order to incorporate the module and configured it as per the demonstration. var app = angular.module ...

Utilizing linked lists in the C programming language

I am currently working on a project that involves 3 files - String (for handling characters and creating strings), the LinkedList file, and main (test file). The String part is functioning perfectly as it has been thoroughly tested. However, I have encount ...

The default.vue layout will be reverted to its original state upon restarting the nuxt.js server

I'm currently learning vue.js within the nuxtjs server environment on localhost:3000. One issue I've encountered is that every time I add a new file named "xxxx.vue" to the "pages" directory or restart the nuxt.js server, it ...

Creating two pointers in a C program to allocate memory for a dynamic array

(edit) I'm seeking clarification on why the allocation of a dynamic array involves two pointers in this code snippet that seemingly functions without issues. int main(int argc, char** argv) { int i; int n=3; int* *t1; *t1 = (int*) mal ...

The definitive method for resolving synchronization problems between Protractor and Angular

The Issue at Hand: We recently encountered a common error while attempting to open a specific page in our application during a Protractor end-to-end test: Error: We timed out waiting for asynchronous Angular tasks to complete after 50 seconds. This cou ...

Iterating over form elements in JavaScript and appending the retrieved values

I am currently working on a form that will automatically calculate the subtotal values based on user input. The form is designed to calculate the values in every input field where "subtotal" appears at the beginning of the name attribute: <script type= ...

Repetitive ajax requests using jquery

When users select multiple checkboxes, I need to make a jQuery ajax call based on their selections. To achieve this, I have implemented a FOR loop to iterate through the selected elements array and send an ajax request for each checkbox. However, each requ ...

Tips for eliminating characters from the console output within a C program

Snippet1: #include<stdio.h> int main() { unsigned short i, j, k; for (i = 0; i < 2; i++) { k = i * 4 + 4; for (j = k - 4; j < k; j++) printf("%hu ", j); putchar('\n'); } ...