Skip to content

Should I worry about using forget method with Closure? #3007

Discussion options

You must be logged in to vote

Using forget is fine as long as you only call it once or a fixed number of times. So in your case, it's fine as long as you only set onsubmit once upon startup.

Here's an example of a case where forget shouldn't be used:

use wasm_bindgen::prelude::*;

#[wasm_bindgen]
extern "C" {
    fn requestAnimationFrame(callback: &Closure<dyn FnMut()>);
}

#[wasm_bindgen(start)]
pub fn start() {
    // Start the rAF loop.
    frame_handler();
}

fn frame_handler() {
    let closure = Closure::new(frame_handler);
    requestAnimationFrame(&closure);

    // Don't do this - this will leak memory every frame.
    closure.forget();
}

Since this example uses the same closure every time, we can instead cre…

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by blueowlgreenfish
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants