1

This function works (suspends the call) but the search value is not updated. If I enter "hello" the value passed to the function ($(this).val()) is "he". Is there a way to update it the key value so that it passes the whole search?.

$('#search').keyup(function () {

  if ($(this).val().length > 1) {
    var searchthis = $(this).val()

    if (srun === 1 && stimer) {
      if (stimer) {
        window.clearTimeout(stimer)
      }

    } else {
      srun = 1
      var stimer = setTimeout(loadsearch(searchthis), 2000)
    }
  }

})  

loadsearch() sets the var srun to 0;

The Fool
  • 16,715
  • 5
  • 52
  • 86
Robert
  • 59
  • 1
  • 5
  • can you show us the loadsearch function please? If its not a higher order function, you should not invoke it while passing it to set timeout. Then you should use `setTimeout(() => loadsearch(searchthis), 1000*2)` – The Fool Dec 15 '19 at 18:53
  • Need a test case verifiable. Do a console.log of searchthis to debug – Thanh Trung Dec 15 '19 at 18:53
  • The problem is in the parentheses here: loadsearch(searchthis). Have a look here https://stackoverflow.com/questions/4120781/settimeout-ignores-timeout-fires-immediately and here: https://stackoverflow.com/questions/2037203/why-is-my-function-call-that-should-be-scheduled-by-settimeout-executed-immediat – Hans Dash Dec 15 '19 at 19:43
  • and then there probably is also a problem with the value searchthis that is made at the moment of keyup, not after the timeout fires. – Hans Dash Dec 15 '19 at 19:47

1 Answers1

0

Apparently, loadSearch is only called once when srun is not set. You should organize your code like this

//put timer outside
var stimer;
$('#search').keyup(function(e) {  
    if ($(this).val().length <= 1) {
        return;
    }

    var searchthis = $(this).val();

    window.clearTimeout(stimer);

    stimer = setTimeout(function() {
        loadsearch(searchthis);
    }, 2000);       
});

setTimeout expect 1st parameter to be a callable function, therefore setTimeout(function(){})

If you put setTimeout(loadsearch(searchthis)) it will execute the loadSearch function directly without waiting for 2s.

Thanh Trung
  • 3,566
  • 3
  • 31
  • 42