延时校验AJAX请求

如果你写过验证用户输入,比如onkeypress那你就会知道,有时你想减少交互的次数运行你的校验函数。你不想打服务器在每个按键,因为大多数用户可以写自己的名字在大约秒,所以你应该较少Ajax请求,直到输入是休眠了100 ms。
那么这是一个好的例子是基于Ajax的用户名验证。

function throttle(fn, delay) {
var timer = null;
return function () {
var context = this, args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(context, args);
}, delay);
};
}

所以,如果你是做一些与jQuery,像一个按键验证,你可以这么做:

$('input.username').keypress(throttle(function (event) {
// do the Ajax request
}, 250));

文章来源:http://remysharp.com/2010/07/21/throttling-function-calls/

作者:达奇
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/dachie/p/2648818.html