|
62 | 62 | var queue = []; |
63 | 63 | var start; |
64 | 64 | var cancelTimer; |
| 65 | + var runScheduledForNextTick; |
65 | 66 |
|
66 | 67 | // returns `fn` wrapped in a function that queues up each call event to be |
67 | 68 | // invoked later inside fo runNow() |
|
77 | 78 | } |
78 | 79 |
|
79 | 80 | // clears the current wait timer and creates a new one |
80 | | - // however, if maxWait is exceeded, calls runNow() immediately |
| 81 | + // however, if maxWait is exceeded, calls runNow() on the next tick. |
81 | 82 | function resetTimer() { |
82 | 83 | if( cancelTimer ) { |
83 | 84 | cancelTimer(); |
84 | 85 | cancelTimer = null; |
85 | 86 | } |
86 | 87 | if( start && Date.now() - start > maxWait ) { |
87 | | - utils.compile(runNow); |
| 88 | + if(!runScheduledForNextTick){ |
| 89 | + runScheduledForNextTick = true; |
| 90 | + utils.compile(runNow); |
| 91 | + } |
88 | 92 | } |
89 | 93 | else { |
90 | 94 | if( !start ) { start = Date.now(); } |
|
96 | 100 | function runNow() { |
97 | 101 | cancelTimer = null; |
98 | 102 | start = null; |
| 103 | + runScheduledForNextTick = false; |
99 | 104 | var copyList = queue.slice(0); |
100 | 105 | queue = []; |
101 | 106 | angular.forEach(copyList, function(parts) { |
|
114 | 119 | * @param {int} [maxWait] max milliseconds to wait before sending out, defaults to wait * 10 or 100 |
115 | 120 | */ |
116 | 121 | debounce: function(fn, ctx, wait, maxWait) { |
117 | | - var start, cancelTimer, args; |
| 122 | + var start, cancelTimer, args, runScheduledForNextTick; |
118 | 123 | if( typeof(ctx) === 'number' ) { |
119 | 124 | maxWait = wait; |
120 | 125 | wait = ctx; |
|
130 | 135 | if( !maxWait ) { maxWait = wait*10 || 100; } |
131 | 136 |
|
132 | 137 | // clears the current wait timer and creates a new one |
133 | | - // however, if maxWait is exceeded, calls runNow() immediately |
| 138 | + // however, if maxWait is exceeded, calls runNow() on the next tick. |
134 | 139 | function resetTimer() { |
135 | 140 | if( cancelTimer ) { |
136 | 141 | cancelTimer(); |
137 | 142 | cancelTimer = null; |
138 | 143 | } |
139 | 144 | if( start && Date.now() - start > maxWait ) { |
140 | | - utils.compile(runNow); |
| 145 | + if(!runScheduledForNextTick){ |
| 146 | + runScheduledForNextTick = true; |
| 147 | + utils.compile(runNow); |
| 148 | + } |
141 | 149 | } |
142 | 150 | else { |
143 | 151 | if( !start ) { start = Date.now(); } |
144 | 152 | cancelTimer = utils.wait(runNow, wait); |
145 | 153 | } |
146 | 154 | } |
147 | 155 |
|
148 | | - // Clears the queue and invokes all of the functions awaiting notification |
| 156 | + // Clears the queue and invokes the debounced function with the most recent arguments |
149 | 157 | function runNow() { |
150 | 158 | cancelTimer = null; |
151 | 159 | start = null; |
| 160 | + runScheduledForNextTick = false; |
152 | 161 | fn.apply(ctx, args); |
153 | 162 | } |
154 | 163 |
|
|
0 commit comments