From Wasm by Example - Hello World.


Rust wasm library lib.rs:

// The wasm-pack uses wasm-bindgen to build and generate JavaScript binding file.
// Import the wasm-bindgen crate.
use wasm_bindgen::prelude::*;

// Our Add function
// wasm-pack requires "exported" functions
// to include #[wasm_bindgen]
#[wasm_bindgen]
pub fn add(a: i32, b: i32) -> i32 {
    return a + b;
}

Script loading wasm, calling the function and updating the result:

import init from "wasm-concepts-hello-world";

const runWasm = async () => {
  // Instantiate our wasm module
  const helloWorld = await init();

  setInterval(() => {
    // Call the Add function export from wasm, save the result
    const addResult = helloWorld.add(Math.random() * 100, Math.random() * 100);
    // Set the result onto the body
    document.getElementById("add-result")!.textContent = `${addResult}`;
  }, 1000);
};

runWasm();

HTML span for the result:

addResult: <span id="add-result"></span>

Live example ➡️ addResult: