Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: setTimeout() - help needed

I'm currently doing a highlighting function on a webpage and im using the jquery plugin for that. My code looks like this:

var input = function() {         
    var matchword = $('#searchbox').val();
    if(matchword != "") {
        $('body').removeHighlight();
        $('body').highlight($('#searchbox').val());
    }
}

$(document).ready(function() {
    $('#searchbox').keyup(function() {
        setTimeout("input()", 2000);    
    });
});

It works fine if there is not so large amount of data on the page. But in case of large amount of data on the page the whole process is slowing down which causes that inputbox is freezing untill the letter is hightlighted. So the typing is not smooth. I tryed to use a setTimeout but it seems doesnt help. Any ideas?

like image 365
ilkin Avatar asked Jan 23 '23 07:01

ilkin


1 Answers

Please don't pass setTimeout a string, there's no need in this case, you can call the function directly like this:

$(function() {
    $('#searchbox').keyup(function() {
       if($(this).data("timeout")) clearTimeout($(this).data("timeout"));
        $(this).data("timeout", setTimeout(input, 2000));
    });
});

As for the other problem of queueing up highlights, you just need to clear the previous timeout (from up to 2 seconds ago) first like above. Also, you can store this timeout locally on the element using .data() like I have above, fewer global variables and you could use this across many elements instead of a timeout variable for each.

like image 117
Nick Craver Avatar answered Feb 01 '23 16:02

Nick Craver