Handling keyup events with throttle or debounce in Javascript/jQuery

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;







up vote
0
down vote

favorite












In my web application, there is a search input field, and when the user empties all of the text inside the input field, there is an API call made for a default-list of results, which are displayed in a dropdown right underneath the input field.



I'm using the keyup event to try to capture when the user will have completed deleting text, but I've not been able to re-create the desired behavior without using setTimeout(). I've been told to use a throttle or debounce method (no third party modules or plugins, although plain jQuery is ok).



Could someone please give me some advice on how to recreate this code without using setTimeout? I've been on this for a couple days no with no luck, any help is appreciated!



(function () 
var desktopInput = document.getElementById('someId');
var desktopResults = document.getElementsByClassName('someClass')[0];

function getSuggestedSearchResults(cb)
$.ajax(
url: url,
data: ,
timeout: REQ_TIMEOUT,
xhrFields:
withCredentials: true
,
success: function (data)
cb(data);

);


function handleEmptyInputDesktop()
if (desktopInput.value === '')
setTimeout(function ()
getSuggestedSearchResults(function (data)
var model = transformResults(data);
var results = nunjucks.render('_fullscreenSearchResults',
results: model,
source: 'suggested'
);
desktopResults.innerHTML = results;
);
, 500);



function init()
desktopInput.addEventListener('keyup', handleEmptyInputDesktop);


init();
)();


Without the setTimeout(), the dropdown menu will disappear if the key isn't pressed long enough on the first stroke that deletes all the text.



I've omitted some extraneous code from this snippet, but I'm happy to give more details if you like.







share|improve this question

















  • 1




    Perhaps you would find this related post: Alternative to setInterval and setTimeout interesting
    – Sam Onela
    May 8 at 22:52

















up vote
0
down vote

favorite












In my web application, there is a search input field, and when the user empties all of the text inside the input field, there is an API call made for a default-list of results, which are displayed in a dropdown right underneath the input field.



I'm using the keyup event to try to capture when the user will have completed deleting text, but I've not been able to re-create the desired behavior without using setTimeout(). I've been told to use a throttle or debounce method (no third party modules or plugins, although plain jQuery is ok).



Could someone please give me some advice on how to recreate this code without using setTimeout? I've been on this for a couple days no with no luck, any help is appreciated!



(function () 
var desktopInput = document.getElementById('someId');
var desktopResults = document.getElementsByClassName('someClass')[0];

function getSuggestedSearchResults(cb)
$.ajax(
url: url,
data: ,
timeout: REQ_TIMEOUT,
xhrFields:
withCredentials: true
,
success: function (data)
cb(data);

);


function handleEmptyInputDesktop()
if (desktopInput.value === '')
setTimeout(function ()
getSuggestedSearchResults(function (data)
var model = transformResults(data);
var results = nunjucks.render('_fullscreenSearchResults',
results: model,
source: 'suggested'
);
desktopResults.innerHTML = results;
);
, 500);



function init()
desktopInput.addEventListener('keyup', handleEmptyInputDesktop);


init();
)();


Without the setTimeout(), the dropdown menu will disappear if the key isn't pressed long enough on the first stroke that deletes all the text.



I've omitted some extraneous code from this snippet, but I'm happy to give more details if you like.







share|improve this question

















  • 1




    Perhaps you would find this related post: Alternative to setInterval and setTimeout interesting
    – Sam Onela
    May 8 at 22:52













up vote
0
down vote

favorite









up vote
0
down vote

favorite











In my web application, there is a search input field, and when the user empties all of the text inside the input field, there is an API call made for a default-list of results, which are displayed in a dropdown right underneath the input field.



I'm using the keyup event to try to capture when the user will have completed deleting text, but I've not been able to re-create the desired behavior without using setTimeout(). I've been told to use a throttle or debounce method (no third party modules or plugins, although plain jQuery is ok).



Could someone please give me some advice on how to recreate this code without using setTimeout? I've been on this for a couple days no with no luck, any help is appreciated!



(function () 
var desktopInput = document.getElementById('someId');
var desktopResults = document.getElementsByClassName('someClass')[0];

function getSuggestedSearchResults(cb)
$.ajax(
url: url,
data: ,
timeout: REQ_TIMEOUT,
xhrFields:
withCredentials: true
,
success: function (data)
cb(data);

);


function handleEmptyInputDesktop()
if (desktopInput.value === '')
setTimeout(function ()
getSuggestedSearchResults(function (data)
var model = transformResults(data);
var results = nunjucks.render('_fullscreenSearchResults',
results: model,
source: 'suggested'
);
desktopResults.innerHTML = results;
);
, 500);



function init()
desktopInput.addEventListener('keyup', handleEmptyInputDesktop);


init();
)();


Without the setTimeout(), the dropdown menu will disappear if the key isn't pressed long enough on the first stroke that deletes all the text.



I've omitted some extraneous code from this snippet, but I'm happy to give more details if you like.







share|improve this question













In my web application, there is a search input field, and when the user empties all of the text inside the input field, there is an API call made for a default-list of results, which are displayed in a dropdown right underneath the input field.



I'm using the keyup event to try to capture when the user will have completed deleting text, but I've not been able to re-create the desired behavior without using setTimeout(). I've been told to use a throttle or debounce method (no third party modules or plugins, although plain jQuery is ok).



Could someone please give me some advice on how to recreate this code without using setTimeout? I've been on this for a couple days no with no luck, any help is appreciated!



(function () 
var desktopInput = document.getElementById('someId');
var desktopResults = document.getElementsByClassName('someClass')[0];

function getSuggestedSearchResults(cb)
$.ajax(
url: url,
data: ,
timeout: REQ_TIMEOUT,
xhrFields:
withCredentials: true
,
success: function (data)
cb(data);

);


function handleEmptyInputDesktop()
if (desktopInput.value === '')
setTimeout(function ()
getSuggestedSearchResults(function (data)
var model = transformResults(data);
var results = nunjucks.render('_fullscreenSearchResults',
results: model,
source: 'suggested'
);
desktopResults.innerHTML = results;
);
, 500);



function init()
desktopInput.addEventListener('keyup', handleEmptyInputDesktop);


init();
)();


Without the setTimeout(), the dropdown menu will disappear if the key isn't pressed long enough on the first stroke that deletes all the text.



I've omitted some extraneous code from this snippet, but I'm happy to give more details if you like.









share|improve this question












share|improve this question




share|improve this question








edited Jun 3 at 6:39
























asked May 8 at 22:23









Aaron Goldsmith

12510




12510







  • 1




    Perhaps you would find this related post: Alternative to setInterval and setTimeout interesting
    – Sam Onela
    May 8 at 22:52













  • 1




    Perhaps you would find this related post: Alternative to setInterval and setTimeout interesting
    – Sam Onela
    May 8 at 22:52








1




1




Perhaps you would find this related post: Alternative to setInterval and setTimeout interesting
– Sam Onela
May 8 at 22:52





Perhaps you would find this related post: Alternative to setInterval and setTimeout interesting
– Sam Onela
May 8 at 22:52











1 Answer
1






active

oldest

votes

















up vote
0
down vote



accepted










I ended up using window.requestAnimationFrame and it worked really well, just thought I'd share my solution based on the linked article.



 function requestAnimationTimeout(callback, delay) 
var dateNow = Date.now;
var requestAnimation = window.requestAnimationFrame;
var start = dateNow();
var stop;

var timeoutFunc = function ()
if (dateNow() - start < delay) requestAnimation(timeoutFunc);
else
return callback();

;

requestAnimation(timeoutFunc);




And then simply use requestAnimationTimeout in place of the native setTimeout.






share|improve this answer





















    Your Answer




    StackExchange.ifUsing("editor", function ()
    return StackExchange.using("mathjaxEditing", function ()
    StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
    StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
    );
    );
    , "mathjax-editing");

    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "196"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    convertImagesToLinks: false,
    noModals: false,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );








     

    draft saved


    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f193964%2fhandling-keyup-events-with-throttle-or-debounce-in-javascript-jquery%23new-answer', 'question_page');

    );

    Post as a guest






























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote



    accepted










    I ended up using window.requestAnimationFrame and it worked really well, just thought I'd share my solution based on the linked article.



     function requestAnimationTimeout(callback, delay) 
    var dateNow = Date.now;
    var requestAnimation = window.requestAnimationFrame;
    var start = dateNow();
    var stop;

    var timeoutFunc = function ()
    if (dateNow() - start < delay) requestAnimation(timeoutFunc);
    else
    return callback();

    ;

    requestAnimation(timeoutFunc);




    And then simply use requestAnimationTimeout in place of the native setTimeout.






    share|improve this answer

























      up vote
      0
      down vote



      accepted










      I ended up using window.requestAnimationFrame and it worked really well, just thought I'd share my solution based on the linked article.



       function requestAnimationTimeout(callback, delay) 
      var dateNow = Date.now;
      var requestAnimation = window.requestAnimationFrame;
      var start = dateNow();
      var stop;

      var timeoutFunc = function ()
      if (dateNow() - start < delay) requestAnimation(timeoutFunc);
      else
      return callback();

      ;

      requestAnimation(timeoutFunc);




      And then simply use requestAnimationTimeout in place of the native setTimeout.






      share|improve this answer























        up vote
        0
        down vote



        accepted







        up vote
        0
        down vote



        accepted






        I ended up using window.requestAnimationFrame and it worked really well, just thought I'd share my solution based on the linked article.



         function requestAnimationTimeout(callback, delay) 
        var dateNow = Date.now;
        var requestAnimation = window.requestAnimationFrame;
        var start = dateNow();
        var stop;

        var timeoutFunc = function ()
        if (dateNow() - start < delay) requestAnimation(timeoutFunc);
        else
        return callback();

        ;

        requestAnimation(timeoutFunc);




        And then simply use requestAnimationTimeout in place of the native setTimeout.






        share|improve this answer













        I ended up using window.requestAnimationFrame and it worked really well, just thought I'd share my solution based on the linked article.



         function requestAnimationTimeout(callback, delay) 
        var dateNow = Date.now;
        var requestAnimation = window.requestAnimationFrame;
        var start = dateNow();
        var stop;

        var timeoutFunc = function ()
        if (dateNow() - start < delay) requestAnimation(timeoutFunc);
        else
        return callback();

        ;

        requestAnimation(timeoutFunc);




        And then simply use requestAnimationTimeout in place of the native setTimeout.







        share|improve this answer













        share|improve this answer



        share|improve this answer











        answered May 9 at 7:21









        Aaron Goldsmith

        12510




        12510






















             

            draft saved


            draft discarded


























             


            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f193964%2fhandling-keyup-events-with-throttle-or-debounce-in-javascript-jquery%23new-answer', 'question_page');

            );

            Post as a guest













































































            Popular posts from this blog

            Chat program with C++ and SFML

            Function to Return a JSON Like Objects Using VBA Collections and Arrays

            Will my employers contract hold up in court?