简体   繁体   English

仅在所选文本稳定时运行该操作

[英]Run the action only when the selected text is stable

I would like to set a timer for the action function.我想为action function 设置一个计时器。 The rule is: when the selected text does not change for 3 seconds, we run the function action with the selected text .规则是:当所选文本不更改3秒时,我们运行function使用所选文本action

I tried the following code in the playground https://microsoft.github.io/monaco-editor/playground.html , it did not work.我在操场上尝试了以下代码https://microsoft.github.io/monaco-editor/playground.html ,它没有工作。 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.编辑 1:我的组件是 class 组件,所以我不能使用挂钩调用。

setTimeout takes function as input, while you have called it. setTimeout将 function 作为输入,而您已调用它。 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);
    } 
})

You can use lodash 's debounce to achieve the effect you want.你可以使用lodashdebounce来达到你想要的效果。 And use useCallback to make sure you get the same instance of function.并使用useCallback确保您获得相同的 function 实例。 I think an implementation like this might work:我认为这样的实现可能有效:

import _ from 'lodash';

...

const debouncedAction = useCallback(_.debounce(action, 3000), []);

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.我用这个作为参考。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM