JS定时器,setTimeout和setInterval的介绍使用

setTimeout:在指定时间后仅执行一次。代码如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body></body>
<script>
    // 定时器 异步运行
    function hello() {
        alert("hello");
    }
    function byebye() {
        alert("byebye");
    }
    // 使用方法名字执行方法
    var t1 = window.setTimeout(hello, 1000);
    // 使用方法名字符串执行方法
    var t2 = window.setTimeout("byebye()", 3000);
    // 去掉定时器
    window.clearTimeout(t1); //当调用该方法时,你会发现并不会出现hello的弹出框
</script> 

</html>

setInterval:以指定时间为周期循环执行,代码如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body></body>
<script>
       //实时刷新时间单位为毫秒
       setInterval('refreshEachSecond()', 5000); // 此处不要设置为一秒去测试,你会发现根本关闭不来,一直弹出
       /* 刷新查询 */
       function refreshEachSecond(){
             alert("refresh every five second");
       }
</script> 

</html>

setInterval:以指定时间为周期循环执行,满足条件时,停止循环,代码如下:

    // 创建定时器
    var name = setInterval(
        function() {
             alert("lalalala");
             if (1 == 1) {
                  // 清除定时任务 
                  clearInterval(name);
             }
        }   ,
        // 每秒执行一次
        1000
    );

猜你喜欢

转载自blog.csdn.net/ysh598923879/article/details/81098170