Date对象和定时器

158 阅读1分钟

Date对象

Date.now() 返回自 1970 年 1 月 1 日 00:00:00 (UTC) 到当前时间的毫秒数

var time = new Date()
var year = time.getFullYear() // 年
var month = time.getMonth() + 1 // 月
var day = time.getDate() // 日
var hour = time.getHours() // 小时
var minutes = time.getMinutes() // 分钟
var second = time.getSeconds() // 秒
var millSecond = time.getMilliseconds() 毫秒
var timer = time.getTime() // 表示从1970年1月1日0时0分0秒(UTC,即协调世界时)距离该日期对象所代表时间的毫秒数
var week = time.getDay() // 返回一个0到6之间的整数值,代表星期几: 0 代表星期日, 1 代表星期一,2 代表星期二, 依次类推

日期格式化

<script>
    /*
      Date.now()获取毫秒数
      日期格式化:var time = new Date();
      time.format("YYYY-MM-DD hh-mm-ss");
    */
    Date.prototype.format = function(fmt) {
      // 获取年月日,时分秒毫秒,季度
      var o = {
        "M+": this.getMonth() + 1,  // 月
        "D+": this.getDate(),  // 日
        "h+": this.getHours(),  // 小时
        "m+": this.getMinutes(), // 分
        "s+": this.getSeconds(), // 秒
        "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
        "S": this.getMilliseconds() // 毫秒
      }
      if(/(Y+)/.test(fmt)){
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substring(4 - RegExp.$1.length));
      }
      for(var k in o){
        if(new RegExp("(" + k + ")").test(fmt)) {
          fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substring(("" + o[k]).length)));
        }
      }
      return fmt;
    }
</script>

定时器

  • 缺陷:定时器不准
  • 原因:js单线程,在执行每个js任务都是按‘轮转时间片’进行排列,等待执行。定时器就是按照设定的时间将任务放到队列中排队等待被执行,存在等待时间,因此不准。(事件轮循)

设置定时器:var timer = setInterval(fn, delay)

清除定时器:clearInterval(timer)

var timer = setTimeout(fn, delay)

clearTimeout(timer)

防抖

  • 一段时间内,以最后一次为准
  • 应用:搜索框,通过@input去监听,可以使用防抖,避免频繁触发
function debounce(fn, delay) {
    var timer = null;
    return function () {
        if (timer) {
            clearTimeout(timer)
            timer = null
        }
        timer = setTimeout(() => {
            fn.apply(this, arguments)
        }, delay)
    }
}

节流

  • 每隔一段时间,执行一次
  • 应用:监听滚动条滚动事件,每隔一段时间执行一次
function throttle(fn, delay) {
    var timer = null
    return function () {
        if (timer) {
            return
        } else {
            timer = setTimerout(() => {
                fn.apply(this, arguments)
            }, delay)
        }
    }
}