Home  >  Q&A  >  body text

javascript - lodash里的_.delay(func, wait, [args])和setTimeout有区别吗?

效果也是在wait时间之后执行func,也能用clearTimeout来清除。
_.defer(func, [args])和setTimeout(func,1)应该也是一样的吧?
_.slice之类的,作用也和原生函数是一样的吧?
所以我想知道为什么要提供这些API?
__
_.slice我知道了,可以处理类数组元素。

伊谢尔伦伊谢尔伦2653 days ago319

reply all(1)I'll reply

  • PHP中文网

    PHP中文网2017-04-11 12:01:33

    import toNumber from './toNumber.js'
    
    /**
     * 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) {
      if (typeof func != 'function') {
        throw new TypeError('Expected a function')
      }
      return setTimeout(func, toNumber(wait) || 0, ...args)
    }
    
    export default delay
    

    我把源码贴出来了,其实就是做了一层封装,本质上没什么区别,但是加了错误处理,并提供了一些附加解决方法,提高了容错率吧

    reply
    0
  • Cancelreply