在KeyPress上触发事件占用的CPU过多 [英] Triggering an Event on KeyPress is too CPU Consuming

查看:149
本文介绍了在KeyPress上触发事件占用的CPU过多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下脚本来过滤掉收件箱中不包含文本的div. (类似于Facebook上的朋友"标签)

I am using the following script to filter out divs that do not contain text in an inbox. (Similar to friends tab on Facebook)

$('#friend_search_form input').keyup(function(){
    var $searchString = $(this).val();
    $('.buddy').show();
    $('.buddy_name > a:contains('+$searchString+')').closest('.buddy').hide();
    console.log($searchString);  
})

问题在于,当您键入内容时,它会占用大量资源并导致儿童车开动.

The problem is when you are typing, it takes a lot of resources and get buggy.

写这个的更好的方法是什么?

What is the better way to write this?

推荐答案

与其在每次按键时都运行您的代码,为什么不等到用户停止输入一段时间?

Instead of running your code every keypress, why not wait until the user stops typing for a period of time?

var typingTimeout;

$('#friend_search_form input').keyup(function(e) { 
  if (typingTimeout != undefined) {
    clearTimeout(typingTimeout);
  }

  typingTimeout = setTimeout(function() {        
    var $searchString = $(this).val();

    $('.buddy').show();
    $('.buddy_name > a:contains('+$searchString+')').closest('.buddy').hide();
    console.log($searchString);  
  }, 500);
});   

这篇关于在KeyPress上触发事件占用的CPU过多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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