+new Date() 使用

189 阅读1分钟

最后会返回时间戳,和 valueOf() 一样, +new Date() 会调用 Date.prototype 上面的 valueOf 方法

const now = +new Date();
console.log(now); // 1610676183172 


const s = new Date();
console.log(s.valueOf()); // 1610676511068


const ss = new Date();
console.log(s.getTime()); // 1610676743954

应用

// 节流
export function _throttle(fn, interval) {
  let last;
  let timer;
  const intervals = interval || 200;
  return function() {
    const that = this;
    const args = arguments;
    let now = +new Date();
    if (last && now - last < interval) {
      clearTimeout(timer);
      timer = setTimeout(function() {
        last = now;
        fn.apply(that, args);
      }, intervals);
    } else {
      last = now;
      fn.apply(that, args);
    }
  };
}

参考