jingchaocheng / Lodash

Lodash 源码解析
MIT License
0 stars 1 forks source link

delay #33

Open jingchaocheng opened 4 years ago

jingchaocheng commented 4 years ago

延迟 wait 毫秒后调用 func。 调用时,任何附加的参数会传给 func

/**
 * Invokes `func` after `wait` milliseconds. Any additional arguments are
 * provided to `func` when it's invoked.
 *
 * @since 0.1.0
 * @category Function
 * @param {Function} func The function to delay.
 * @param {number} wait The number of milliseconds to delay invocation.
 * @param {...*} [args] The arguments to invoke `func` with.
 * @returns {number} Returns the timer id.
 * @example
 *
 * delay(text => console.log(text), 1000, 'later')
 * // => Logs 'later' after one second.
 */
function delay(func, wait, ...args) {
  // 如果 func 不是 function 抛出错误
  if (typeof func !== 'function') {
    throw new TypeError('Expected a function')
  }

  // +wait 转数字类型,
  return setTimeout(func, +wait || 0, ...args)
}

export default delay