Is it possible to throttle documentChanged events?

I'm implementing a "live preview" function in my plugin. I added the document listener to my editor, but it fires every time the user types anything, and this creates a lot of noise. I'm wondering if there's any built-in mechanism which would allow me to throttle those events, e.g. limiting to 1 per second or so.

 

0
4 comments

Eugene, you can implement it using API Alarm class:

import com.intellij.openapi.Disposable;
import com.intellij.util.Alarm;

public class ThrottleDocumentChanged implements Disposable {
    Alarm myDocumentAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD, this);
    //Alarm myDocumentAlarm = new Alarm(Alarm.ThreadToUse.POOLED_THREAD, this);
    static final long MODIFIED_DOCUMENT_TIMEOUT_MS = 50L; 

    @Override
    public void dispose() {

    }

    void updateDocument() {
        if (myDocumentAlarm.isDisposed()) return;

        myDocumentAlarm.cancelAllRequests();
        myDocumentAlarm.addRequest(() -> {
            // put your update code here
        }, MODIFIED_DOCUMENT_TIMEOUT_MS);
    }
}
1

Thanks, Vladimir, that looks good, but how do I add it to my document or document listener?

 

0

Add the members of the ThrottleDocumentChanged to your class that is responsible for updating the preview, if you have a custom editor for the document add it there, and from the DocumentListener call the updateDocument() method to trigger the next update.

The delay in the sample is 50ms, you can make it what you feel gives the best compromise between frequent updates and short enough update delay.

An update will occur 50ms after the last call to updateDocument().

0

Got it, thank you very much! This is precisely what I was looking for!

 

0

Please sign in to leave a comment.