[英]How to throttle my JS API fetch requests, using the rate-limit supplied by the host?
[英]How to rate-limit ajax requests?
有幾個div和處理程序在單擊它們時發送ajax請求。 我的問題是我不知道如何強迫我的處理程序不超過每30秒1個請求的限制。
感謝您的幫助!
優秀的Underscore.js具有節流功能。 您傳入要限制的處理程序並返回相同功能的速率限制版本。
var throttled = _.throttle(someHandler, 100);
$(div).click(throttled);
http://documentcloud.github.com/underscore/#throttle
這是我在自己的代碼中使用的簡化版本:
function throttle(func, wait) {
var timeout;
return function() {
var context = this, args = arguments;
if (!timeout) {
// the first time the event fires, we setup a timer, which
// is used as a guard to block subsequent calls; once the
// timer's handler fires, we reset it and create a new one
timeout = setTimeout(function() {
timeout = null;
func.apply(context, args);
}, wait);
}
}
}
測試它的一個好方法是觸發一堆滾動事件並觀察處理程序日志到Firebug控制台:
document.addEventListener("scroll", throttle(function() {
console.log("test");
}, 2000), false);
這是一個版本,根據請求(需要jQuery)將div
的點擊事件限制為每30秒一次:
$("div").click(throttle(function() {
// ajax here
}, 30000));
如果你想率限制,那么不幸的是,underscore.js提供的_.throttle方法不是你的解決方案。 Throttle將簡單地確保您的方法永遠不會被調用超過X秒,因此所有后續函數調用將被忽略,直到該時間段過去。
如果你想限速,這樣你就不會每秒調用你的函數超過X次,但是不要完全失去那些函數調用,那么你需要一個完全不同的解決方案。
我在https://gist.github.com/1084831寫了一個下划線擴展名
您可以在http://jsbin.com/upadif/8/edit#preview上看到一個工作示例
在每個ajax請求之后創建一個布爾值的canFireRequest或其他標志,並將其設置為false。 然后創建一個30秒的時間跨度,使其恢復為真; 在每個新請求之前檢查標志的值。
這是一個粗略的例子:
if ($(this).data('canFireRequest')) {
// Ajax request goes here
$(this).data('canFireRequest', false);
}
setTimeout(function() {
$(this).data('canFireRequest', true)
}, 30000);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.