How to delay KeyPress function when user is typing, so it doesn't fire a request for each keystroke?

前端 未结 1 418
旧巷少年郎
旧巷少年郎 2021-02-01 17:39

background

I have a number of dropdowns on a page. If you change the first one, the rest of the dropdowns are updated according to what you\'ve selected

1条回答
  •  失恋的感觉
    2021-02-01 17:47

    The way I have done this before is to set a timeout, but clear the existing timeout each time a new key is pressed. That way you should only get the request being sent when the user has stopped typing.

    var timeoutId = 0;
    $('#Search').keypress(function () { 
        clearTimeout(timeoutId); // doesn't matter if it's 0
        timeoutId = setTimeout(getFilteredResultCount, 500);
        // Note: when passing a function to setTimeout, just pass the function name.
        // If you call the function, like: getFilteredResultCount(), it will execute immediately.
    });
    

    (I'd go for about 500ms timeout.)

    0 讨论(0)
提交回复
热议问题