How to debounce in an updateListener?

Whenever the doc changes I would like to POST the text to an endpoint. However I would like to do this with a debounce, as to not spam the API with too much requests.

const onUpdateHandler = EditorView.updateListener.of((update) => {
  if (update.docChanged) {
    const content = update.state.doc.toString();
    // Here I'll do a fetch to the API. 
  }
});

const editor = new EditorView({
  state: EditorState.create({
    doc: `# Hello!\n\n_test_`,
    extensions: [basicSetup, theme, markdown(), onUpdateHandler],
  }),
  parent: editorEl,
});

I’m unsure what a good way is to work a debounce function into that if statement. Normally I would wrap the onUpdateHandler with a debounce, e.g. debounce(onUpdateHandler, 3000).

Or is there maybe a better way to do this? I’ve also considered periodically getting the doc content and submitting that to the API.

1 Like