JS学习笔记 Date对象及定时器操作

1.Date对象基本使用

<script>
    // 1. 声明日期对象
    var date = new Date();
    // console.log(date);

    console.log(date.getDate()); // 日
    console.log(date.getDay()); // 星期几
    console.log(date.getMonth() + 1); // 月
    console.log(date.getFullYear() ); // 完整的年份
    console.log(date.getHours() ); // 小时
    console.log(date.getMinutes() ); // 分钟
    console.log(date.getSeconds() ); // 秒
    console.log(date.getMilliseconds() ); // 毫秒
    console.log(date.getTime() ); // 时间戳
</script>

2.定时器操作

创建以及清除定时器:

<script>
    window.onload = function () {
        // 1.获取需要的标签
        var btn1 = document.getElementById("btn1");
        var btn2 = document.getElementById("btn2");

        var height = 150, timer = null;

        // 2. 开启定时器
        btn1.onclick = function () {
             // 2.1 设置定时器
            timer = setInterval(function () {
                height += 1;
                console.log("身高是" + height + "cm");
            }, 1000);
        };

        // 3. 结束定时器
        btn2.onclick = function () {
            console.log(timer);
            clearInterval(timer);
        }
    }
</script>

但是这种写法可能会出现问题,那就是可能会出现定时器叠加的后果,所以,我们一般都是先清除定时器,再设置定时器。

自定义时间:

<script>
    // 1. 自定义现在的时间
    var currentDate = new Date();
    console.log(currentDate);

    var nextDate = new Date('2018/08/08 08:17:35');
    console.log(nextDate);

    var preDate = new Date('2017/08/08 08:17:35');
    console.log(preDate);
</script>

一次定时器:

<script>
    window.onload = function () {
        // 1. 获取需要的标签
        var btn = document.getElementById("btn");
        var btn1 = document.getElementById("btn1");
        var timer = null;

        // 2. 监听按钮的点击
        btn.onclick = function () {

            clearTimeout(timer);

           // 一次定时器
           timer = setTimeout(function () {
               alert('请你去吃饭');
           }, 3000);
        };

        btn1.onclick = function () {
            clearTimeout(timer);
        }
    }
</script>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值