定时器

133 阅读2分钟

这是我参与11月更文挑战的第24天,活动详情查看:2021最后一次更文挑战

定时器

定时器的具体方法由Window对象提供,共有以下两种定时器:

  • 延迟执行:指的是指定程序代码在指定时间后被执行,而不是立即被执行。
  • 周期执行:指的是指定程序代码在指定时间为间隔,重复被执行。

目前,HTML页面中多数动态效果,以及动画效果等均由定时器内容完成。

延迟执行

setTimeout()方法设置一个定时器,该定时器在定时器到期后执行一个函数或指定的一段代码。

var timeoutID = scope.setTimeout(function/code[,delay]);

该方法的参数如下:

  • function/code:表示要调用的函数或要执行的代码
  • delay:延迟的毫秒数(一秒等于1000毫秒),函数的调用会在该延迟之后发生。如果省略改参数,delay取默认值0。

该方法的返回值timeoutID是一个正整数,表示定时器的编号。这个值可以传递给clearTimeout()来取消该定时。

如下代码展示了延迟执行:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>延迟执行</title>
</head>
<body>
<script>
    console.log('this is message...');
    /*
        setTimeout(function,delay)方法
        * 作用:设置一个定时器
        * 参数
            * function - 表示延迟执行的代码逻辑
            * delay - 表示延迟执行的时间,单位为毫秒
        * 返回值 - 表示当前定时器的标识
        * 注意 - 会打乱代码默认的顺序执行流程
    */
    var t = setTimeout(function () {
        console.log('this is timeout');
    },5000);
    // clearTimeout(t);

    console.log('this is message too...');
</script>
</body>
</html>

周期执行

setlnterval()方法重复调用一个函数或执行一个代码段,在每次调用之间具有固定的时间延迟。

var timeoutlD = scope.setlnterval(function/code[, delay]);

该方法的参数如下:

  • function/code:表示要调用的函数或要执行的代码
  • delay:延迟的毫秒数(一秒等于1000毫秒),函数的调用会在该延迟之后发生。如果省略改参数,delay取默认值0。

该方法的返回值timeoutID是一个正整数,表示定时器的编号。这个值可以传递给clearInterval()来取消该定时。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>延迟执行</title>
</head>
<body>
<script>
    console.log('this is message...');
    /*
        setInterval(function,delay)方法
        * 作用 - 设置一个周期执行的定时器
        * 参数
            * function - 表示延迟执行的代码逻辑
            * delay - 表示延迟执行的时间,单位为毫秒
         * 返回值 - 表示当前定时器的标识
    */
    //周期执行
    /*setInterval(function () {
        console.log('this is interval ...');
    },1000);*/

   /* //延迟执行实现周期执行效果
    function fun(){
        console.log('this is interval ...');
        setTimeout(fun,1000);
    };
    fun();
    */

    // 自调度函数实现周期执行效果
    (function fun() {
        console.log('this is interval...');
        setTimeout(fun,1000);
        // setTimeout(arguments.callee,1000);
    })();

    console.log('this is message too ...')
</script>
</body>
</html>

HTML5的动画方法

requestAnimationFrame()方法告诉浏览器您希望执行动画并请求浏览器在下一次重绘之前调用指定的函数来更新动画。该方法使用一个回调函数作为参数,这个回调函数会在浏览器重绘之前调用。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>HTML5的动画方法</title>
</head>
<body>
<script>
    console.log('this is message...');
    /*
        requestAnimationFrame(callback)方法(类似于延迟执行)
            * 作用 - HTML5 新增的动画方法
            * 参数
              * callback - 表示执行动画逻辑的回调函数
            * 返回值 - 表示当前执行动画的标识
            * 注意 - 具有浏览器兼容问题

            cancelAnimationFrame(animationID)方法
              * 作用 - 取消由requestAnimationFrame()方法设定的动画机制
    * */
    requestAnimationFrame(function () {
        console.log('this is animation...');
    });

    console.log('this is message too...');
</script>
</body>
</html>