A debounce is a higher-order function, which is a function that returns another function * that, as long as it continues to be invoked, will not be triggered. * The function will be called after it stops being called for N milliseconds. * If `immediate` is passed, trigger the function on the lead
(func, wait, immediate)
| 388 | * @Returns a promise that will resolve to func return value. |
| 389 | */ |
| 390 | function debounce(func, wait, immediate) { |
| 391 | if (typeof wait === "undefined") { |
| 392 | wait = 40 |
| 393 | } |
| 394 | if (typeof wait !== "number") { |
| 395 | throw new Error("wait is not an number.") |
| 396 | } |
| 397 | let timeout = null |
| 398 | let lastPromiseSrc = new PromiseSource() |
| 399 | const applyFn = function (context, args) { |
| 400 | let result = undefined |
| 401 | try { |
| 402 | result = func.apply(context, args) |
| 403 | } catch (err) { |
| 404 | lastPromiseSrc.reject(err) |
| 405 | } |
| 406 | if (result instanceof Promise) { |
| 407 | result.then(lastPromiseSrc.resolve, lastPromiseSrc.reject) |
| 408 | } else { |
| 409 | lastPromiseSrc.resolve(result) |
| 410 | } |
| 411 | } |
| 412 | return function (...args) { |
| 413 | const callNow = Boolean(immediate && !timeout) |
| 414 | const context = this |
| 415 | if (timeout) { |
| 416 | clearTimeout(timeout) |
| 417 | } |
| 418 | timeout = setTimeout(function () { |
| 419 | if (!immediate) { |
| 420 | applyFn(context, args) |
| 421 | } |
| 422 | lastPromiseSrc = new PromiseSource() |
| 423 | timeout = null |
| 424 | }, wait) |
| 425 | if (callNow) { |
| 426 | applyFn(context, args) |
| 427 | } |
| 428 | return lastPromiseSrc.promise |
| 429 | } |
| 430 | } |
| 431 | |
| 432 | function preventNonNumericalInput(e) { |
| 433 | e = e || window.event |
no test coverage detected