Search code examples
javascriptjqueryperformancewindowsetinterval

Is window.setInterval correctly used here or am I introducing trouble?


I have a search input.searchinp from a third party that I cannot modify. But I want to move the results from the left side of the page to the right side. I do this currently with a setInterval. The reason I used this setInterval is that the div that I want to move is not present on the page when it is loaded. Therefore I cannot simply move it at that point.

The user needs to fill in at least 3 letters before the results div.dropdown-menu is created.

So to make it move I used this:

      window.setInterval(function(){
        /// call your function here
        $('.dropdown-menu').contents().appendTo('.knowledgebase-related-questions');
      }, 100);

Which works but I would like to know if there are drawbacks to doing this? Like website speed, slugginess or other drawbacks.


Solution

  • If it were me, Id add a listener to the input the user is typing in and set it up with a delay so my function is called X seconds after the user stops typing. Something like this:

    var keyupDelay = (function(){
      var timer = 0;
      return function(callback, ms){
        clearTimeout (timer);
        timer = setTimeout(callback, ms);
      };
    })(); 
    
    
    var inputSelector = '#some-id'; // adjust as needed 
    
    $(inputSelector ).keyup(function() {
        keyupDelay(function(){
          // append or replace your html as needed
        }, 2500 ); // this will trigger 2.5 seconds after typing stops, adjust as needed
    });