JavaScript基础学习 定时器setTimeout与setInterval

JavaScript基础学习 定时器setTimeout与setInterval

定时器setTimeout

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=devcie-width,initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>


</head>

<body>
    <div>

    </div>
    <button>点击停止two-爆炸</button>
    <script>
        //  window.setTimeout(回调函数,延时的时间)  单位:毫秒  如果不加默认为0
        //   window可以省略
        //   当延时时间过去时,才会执行我们这个回调函数
        // 1 第一种写法
        window.setTimeout(function() {
            console.log('one-爆炸了');
        }, 3000);

        // 2. 第二种写法
        function callback() {
            console.log('two-爆炸了');
        }

        // 因为一个页面当中可能会有很多计时器,所以我们可以给计时器定义一个标识符
        // var time1 = setTimeout(callback, 5000);
        var time2 = setTimeout(callback, 5000);

        // 停止定时器  clearTimeout(timeoutId)   参数为定时器的标识符
        var btn = document.querySelector('button');
        btn.addEventListener('click', function() {
            clearTimeout(time2);
        })
    </script>

</body>

</html>

在这里插入图片描述

定时器setInterval

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <button id="begin">开始定时器</button>
    <button id="stop">停止定时器</button>
    <script>
        // 1. setInterval 
        // 语法规范:  window.setInterval(调用函数, 延时时间);
        // setInterval(function() {
        //     console.log('继续输出');

        // }, 1000);
        // 2. setTimeout  延时时间到了,就去调用这个回调函数,只调用一次 就结束了这个定时器
        // 3. setInterval  每隔这个延时时间,就去调用这个回调函数,会调用很多次,重复调用这个函数

        var begin = document.querySelector('#begin');
        var stop = document.querySelector('#stop');
        var timer = null;
        begin.addEventListener('click', function() {
            timer = setInterval(function() {
                console.log('ni hao ma ');
            }, 2000);
        })

        //  停止计时器   clearInterval(标识符)
        stop.addEventListener('click', function() {
            clearInterval(timer);
        })
    </script>
</body>

</html>

</html>

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值