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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With