定时器 延时器

2021-05-20  本文已影响0人  BJ呀呀呀
setInterval() 定时器 重复指定,默认情况下不会终止
setTimeout() 延时器 只会执行1次

(回调函数 长成定时器的模式,就是回调函数,同时它也是一个高阶函数)

setTimeout(函数,时间,参数)

setTimeout(function (str) {
console.log("你好:"+str);
 },3000,"周杰伦");
var fn=function(str){
console.log("你好:"+str);
}
setTimeout会去帮你执行fn,如果会给fn加小括号
 setTimeout(fn,3000,"刘德华");
不好
setTimeout("document.body.remove()",3000);

延时器

<body>
    <button id="start">开始</button>
    <button id="end">暂停</button>

    <script>
        var oStart = document.getElementById("start");
        var oEnd = document.getElementById("end");
        //setInterval()返回编号 (序列号)
        //序列号从1开始
        //点击的时候,会执行函数
        var n; //全局变量
        var n1;//全局变量
        oStart.onclick = function () {
            //定时器
            // setTimeout
            //开启定时器1
            n = setInterval(function (str) {
                console.log("你好:" + str);
            }, 1000, "蔡徐坤")
         
            //开启定时器2
            n1 = setInterval(function (str) {
                console.log("你好:" + str);
            }, 1000, "刘德华")
            console.log(n);
            // console.log(n1);
        }

        oEnd.onclick = function () {
            //暂停
            console.log(n);
            console.log(n1);

            clearInterval(n);
            clearInterval(n1);
        }
    </script>
</body>
上一篇 下一篇

猜你喜欢

热点阅读