Home > front end >  Run the action only when the selected text is stable
Run the action only when the selected text is stable

Time:01-02

I would like to set a timer for the action function. The rule is: when the selected text does not change for 3 seconds, we run the function action with the selected text.

I tried the following code in the playground https://microsoft.github.io/monaco-editor/playground.html, it did not work. When I changed the selected text very quickly, their actions were not cancelled.

Could anyone help?

const editor = monaco.editor.create(document.getElementById('container'), {
    value: '1 2 3 4 5 6 7',
    language: 'javascript'
});

function action(x) {
    console.log("action", x)
}

let myTimeout
editor.onDidChangeCursorSelection((e) => {
    clearTimeout(myTimeout)
    console.log("cleared", myTimeout)
    let selectedText = editor.getModel().getValueInRange(editor.getSelection())
    if (selectedText != "") { // if we are already in this event, the selected text must change
        myTimeout = setTimeout(action(selectedText), 3000);
        console.log("set", myTimeout, selectedText)
    } 
})

Edit 1: My component is a class component, so I cannot use hook calls.

CodePudding user response:

You can use lodash's debounce to achieve the effect you want. And use useCallback to make sure you get the same instance of function. I think an implementation like this might work:

import _ from 'lodash';

...

const debouncedAction = _.debounce(action, 3000).bind(this);

editor.onDidChangeCursorSelection((e) => {
    let selectedText = editor.getModel().getValueInRange(editor.getSelection())
    if (selectedText != "") { // if we are already in this event, the selected text must change
        debouncedAction(selectedText);
    } 
})

I used this as a reference.

CodePudding user response:

setTimeout takes function as input, while you have called it. I think the following code works well.

const editor = monaco.editor.create(document.getElementById('container'), {
    value: '1 2 3 4 5 6 7',
    language: 'javascript'
});

function action(x) {
    console.log("action", x)
}

let myTimeout
editor.onDidChangeCursorSelection((e) => {
    clearTimeout(myTimeout)
     let selectedText = editor.getModel().getValueInRange(editor.getSelection())
    if (selectedText != "") {
        // "action" is called inside a function
        myTimeout = setTimeout(() => action(selectedText), 3000);
    } 
})
  • Related