0

Recently I run into an odd bug, I'm not sure if this is my code bug or is it a problem in JS/Rust Web Assembly.

Long story short I have been trying to call an web assembly async function from js event handler, for some reason the event is keep triggering infinite times. for example for the 'keydown' event once you press a key the handler will be called (You can release the key and it still thinks that you are pressing it) until you switch tab.

code example:
Rust function:

[wasm_bindgen]
pub async fn test() {
     await something();
}

js code:

import the wasm...

document.addEventListener('keydown', keyDownHandler, false)

function keyDownHandler() {
    test();
}

What do you advise me to do? Should I reported it as a bug in the wasm community? Maybe you have a solution for me?

Jason
  • 4,905
  • 1
  • 30
  • 38
boaz tene
  • 71
  • 1
  • 3
  • 2
    The [`keydown`](https://developer.mozilla.org/en-US/docs/Web/API/Document/keydown_event) event in JavaScript is triggered continuously until the button is released or if options such `{ once: true }` were supplied to the event listener. Are you throttling or debouncing the events to make sure a queue of asynchronous calls isn't building up? – Jason Feb 02 '21 at 13:36
  • You should check if its really being called infinite times or if calls are just being queued up as you hold the button and are still being processed when the button is released. If it is the case, please provide a [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example). Or check out [Prevent JavaScript keydown event from being handled multiple times while held down](https://stackoverflow.com/questions/6087959/prevent-javascript-keydown-event-from-being-handled-multiple-times-while-held-do) to avoid it entirely. – kmdreko Feb 02 '21 at 20:45

1 Answers1

0

I finally solved the problem as a result of your comments, so thanks a lot!

What I did was to use the throttling technique, you can also try the debouncing technique.

A nice article that explains both techniques better then I do.

boaz tene
  • 71
  • 1
  • 3