UNPKG

1.21 kBJavaScriptView Raw
1
2
3
4!function(F, undef) {
5 // Time to live - Run *onTimeout* if Function not called on time
6 F.ttl = function(ms, onTimeout, scope) {
7 var fn = this
8 , tick = setTimeout(function() {
9 ms = 0
10 if (onTimeout) onTimeout.call(scope)
11 }, ms)
12
13 return function() {
14 clearTimeout(tick)
15 if (ms) fn.apply(scope === undef ? this : scope, arguments)
16 }
17 }
18
19 // Run Function one time after last call
20 F.once = function(ms, scope) {
21 var tick, args
22 , fn = this
23 return function() {
24 if (scope === undef) scope = this
25 clearTimeout(tick)
26 args = arguments
27 tick = setTimeout(function() {
28 fn.apply(scope, args)
29 }, ms)
30 }
31 }
32
33 // Maximum call rate for Function
34 // leading edge, trailing edge
35 F.rate = function(ms, last_call, scope) {
36 var tick, args
37 , fn = this
38 , next = 0
39 if (last_call && typeof last_call !== "function") last_call = fn
40 return function() {
41 if (scope === undef) scope = this
42 var now = Date.now()
43 clearTimeout(tick)
44 if (now >= next) {
45 next = now + ms
46 fn.apply(scope, arguments)
47 } else if (last_call) {
48 args = arguments
49 tick = setTimeout(function() {
50 last_call.apply(scope, args)
51 }, next - now)
52 }
53 }
54 }
55}(Function.prototype)
56