3

How to avoid repeated requests in the text box, the text box interacting with th...

 3 years ago
source link: https://www.codesd.com/item/how-to-avoid-repeated-requests-in-the-text-box-the-text-box-interacting-with-the-server.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

How to avoid repeated requests in the text box, the text box interacting with the server

advertisements

In Javascript, does someone/anyone have a exhaustive list of key combination to avoid. For example a textbox sending webservice requests for each keypress. It often happens for key combinations like HOME[for cursor returning to start of textbox] , DELETE, SHIFT + HOME + DELETE the event fires and same request params is sent to webservice.[I know caching query results will solve for this scenario but what about other]. I would love to see a list for this, i couldn't find a similar question before hence this Update: Since the earlier question title seemed too way off and likely closable i changed it. I would like to know how to optimize this process of sending request in ajax manner less intensive.


Assuming the user is writing in a textarea or input, you can check the value of that element for each keystroke; if it's different from its last value, send it to the server. If it's the same, then do nothing.

Example:

function updateOnKeypress(input) {
    var lastValue;
    input.addEventListener('keypress', function() {
        if( input.value.trim() !== lastValue ) {
            // trim() isn't available in every browser, but you can add it
            // Of course, if leading/trailing whitespace is supposed to trigger
            // a request, then skip the trim()
            lastValue = input.value.trim();
            // … send value to server
        }
    });
}

You might also want to throttle the number of requests with a timer, so not every change results in a request to the server. For instance, for each change start a timeout (say, 0.3 seconds), and then send the value when the timer executes.

function updateOnKeypressDelayed(input) {
    var lastValue, timer;
    input.addEventListener('keypress', function() {
        if( !timer ) {
            timer = setTimeout(function () {
                if( input.value.trim() !== lastValue ) {
                    lastValue = input.value.trim();
                    timer = null;
                    // … send value to server
                }
            }, 300);
        }
    });
}


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK