Skip to content

Commit d0819e3

Browse files
committed
Issue ohmage#6 - Replace debounce with throttle, reduce max ping by 1 sec to eliminate race condition
1 parent 8ec871f commit d0819e3

File tree

2 files changed

+32
-28
lines changed

2 files changed

+32
-28
lines changed

ohmage.js

+31-27
Original file line numberDiff line numberDiff line change
@@ -483,8 +483,8 @@
483483
});
484484
}
485485

486-
//no more than 1 ping every 60 sec
487-
oh.ping = debounce(oh.user.whoami, 60*1000, true);
486+
//no more than 1 ping every 59 sec
487+
oh.ping = throttle(oh.user.whoami, 59*1000);
488488

489489
//ping once every t sec
490490
oh.keepalive = once(function(t){
@@ -500,41 +500,45 @@
500500
});
501501

502502
// Copied from underscore.js
503-
function debounce(func, wait, immediate) {
504-
var timeout, args, context, timestamp, result;
505-
506-
var now = function() {
507-
return new Date().getTime();
508-
};
503+
function throttle(func, wait, options) {
504+
var timeout, context, args, result;
505+
var previous = 0;
506+
if (!options) options = {};
509507

510508
var later = function() {
511-
var last = now() - timestamp;
512-
if (last < wait) {
513-
timeout = setTimeout(later, wait - last);
514-
} else {
515-
timeout = null;
516-
if (!immediate) {
517-
result = func.apply(context, args);
518-
context = args = null;
519-
}
520-
}
509+
previous = options.leading === false ? 0 : _.now();
510+
timeout = null;
511+
result = func.apply(context, args);
512+
if (!timeout) context = args = null;
521513
};
522514

523-
return function() {
515+
var throttled = function() {
516+
var now = _.now();
517+
if (!previous && options.leading === false) previous = now;
518+
var remaining = wait - (now - previous);
524519
context = this;
525520
args = arguments;
526-
timestamp = now();
527-
var callNow = immediate && !timeout;
528-
if (!timeout) {
529-
timeout = setTimeout(later, wait);
530-
}
531-
if (callNow) {
521+
if (remaining <= 0 || remaining > wait) {
522+
if (timeout) {
523+
clearTimeout(timeout);
524+
timeout = null;
525+
}
526+
previous = now;
532527
result = func.apply(context, args);
533-
context = args = null;
528+
if (!timeout) context = args = null;
529+
} else if (!timeout && options.trailing !== false) {
530+
timeout = setTimeout(later, remaining);
534531
}
535-
536532
return result;
537533
};
534+
535+
throttled.cancel = function() {
536+
clearTimeout(timeout);
537+
previous = 0;
538+
timeout = context = args = null;
539+
};
540+
541+
return throttled;
538542
};
539543

540544
// Copied from underscore.js

ohmage.min.js

+1-1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)