|
483 | 483 | });
|
484 | 484 | }
|
485 | 485 |
|
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); |
488 | 488 |
|
489 | 489 | //ping once every t sec
|
490 | 490 | oh.keepalive = once(function(t){
|
|
500 | 500 | });
|
501 | 501 |
|
502 | 502 | // 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 = {}; |
509 | 507 |
|
510 | 508 | 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; |
521 | 513 | };
|
522 | 514 |
|
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); |
524 | 519 | context = this;
|
525 | 520 | 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; |
532 | 527 | 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); |
534 | 531 | }
|
535 |
| - |
536 | 532 | return result;
|
537 | 533 | };
|
| 534 | + |
| 535 | + throttled.cancel = function() { |
| 536 | + clearTimeout(timeout); |
| 537 | + previous = 0; |
| 538 | + timeout = context = args = null; |
| 539 | + }; |
| 540 | + |
| 541 | + return throttled; |
538 | 542 | };
|
539 | 543 |
|
540 | 544 | // Copied from underscore.js
|
|
0 commit comments