Javascript:setTimeout()-需要帮助 [英] Javascript: setTimeout() - help needed

查看:97
本文介绍了Javascript:setTimeout()-需要帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在网页上执行突出显示功能,为此我正在使用jquery插件.我的代码如下:

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);    
    });
});

如果页面上没有那么多数据,它会很好地工作.但是,如果页面上有大量数据,则整个过程会变慢,这会导致输入框冻结,直到字母被高亮显示为止.因此打字不流畅.我试图使用setTimeout,但似乎没有帮助.有什么想法吗?

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?

推荐答案

在您提供的示例中,setTimeout仅延迟了函数的执行,但是执行次数仍然相同.您需要做的是,每当用户键入一个字符时刷新超时,这样input()函数就不会每次都触发:

In the sample that you have provided, the setTimeout is only delaying the execution of the function, but the number of executions is still the same. What you need to do is, refresh the timeout each time the user types a character, so the input() function does not fire each time:

var timer;

$('#searchbox').keyup(function() {
  clearTimeout(timer);
  timer = setTimeout(input, 2000);
});

这篇关于Javascript:setTimeout()-需要帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆