使用JavaScript的setTimeout延迟AJAX搜索

I was recently creating a custom Dijit widget that required that a list get filtered during each keystroke instead of using the usual "Submit" button.  The problem I ran into (and had anticipated) was that each keystroke made the list flicker and fire off numerous AJAX requests.  The normal flow was:

我最近创建了一个自定义的Dijit小部件,该小部件要求在每次击键期间都对列表进行过滤,而不是使用通常的“提交”按钮。 我遇到(并曾预料到)的问题是每次击键都会使列表闪烁并触发大量AJAX请求。 正常流程为:


D
Da
Dav
Davu // Oops, mistyped!
Dav
Davi
David
David_ // Space
David_W //...and so on


Users that type quickly don't need a list filtered during every keystroke -- that's a waste of client-side processing.  The simple solution is to employ JavaScript's native setTimeout method to delay searches until a given idle-time has passed.  Users who type quickly thus wont bog down the page.

快速键入的用户不需要在每次击键时都过滤列表,这浪费了客户端处理。 简单的解决方案是使用JavaScript的本机setTimeout方法将搜索延迟到给定的空闲时间过去。 快速键入的用户因此不会陷入页面混乱。


// Add an onChange to the textbox to listen to typing/changes
this.findTextbox.lastValue = "";
var timeout;
dojo.connect(this.findTextbox,"onKeyUp",this,function(){
	// Only fire change if value has changed
	var value = this.findTextbox.get("value");
	if(value != this.findTextbox.lastValue) {
		// Save the "last" value
		this.findTextbox.lastValue = value;
		// Delay before search in the case of typing
		if(timeout) { clearTimeout(timeout); }
		// Start new time out
		timeout = setTimeout(function() {
			// Do the search!
			console.warn("Doing search for " + value + ", time waited");
			// Process....
		},this.findKeyDelay);
	}
});


It's important to store the last value of the input so that "useless" keys like SHIFT, CONTROL, and others don't trigger a restart of the timer.  If the key does change the value of the input element before the timer is met, the timer is clear and restarted!  You'll notice that I do not ensure that a value is present -- that's because I want the field to return all results if the user filters something and then deletes the input!  This type of timer solution will save loads of unwanted processing on both the client and server sides!

存储输入的最后一个值很重要,这样SHIFTCONTROL等“无用的”键不会触发计时器的重启。 如果按键确实在满足计时器之前更改了输入元素的值,则计时器将清除并重新启动! 您会注意到,我不保证存在一个值-这是因为如果用户过滤某些内容然后删除输入,我希望该字段返回所有结果! 这种计时器解决方案将节省客户端和服务器端不必要的处理工作!

翻译自: https://davidwalsh.name/javascript-settimeout

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值