Fast repeated input using javascript keyboard button leads contents loss or sometimes crash


I have added a keyboard extension button to insert some characters at cursor position.

When I press the button repeatedly and fast, about 4~5 times a second, text in the editor gets cut off.

I recorded video.

You can see the word count goes up and drops when the issue occurs.

the script I wrote is the following:

const c = “j”;

let sel = editor.getSelectedText();
let selRange = editor.getSelectedRange();

if (!sel || sel.length == 0) {
editor.setSelectedRange(selRange[0] + c.length, 0);
} else {
editor.setSelectedText(c + sel);
editor.setSelectedRange(selRange[0] + selRange[1] + c.length, 0);

My guess is that this would be related to background syncing.

Any solution or workaround would be very appreciated.

Thanks in advance.

I turn on/off icloud sync from settings menu and I could see that when the sync is off, cut-off does not happen.