zoukankan      html  css  js  c++  java
  • JavaScript定时器

    1、设置定时器
    定时器,适用于定时执行的任务中。在BOMwindow对象中,有这样的两个函数是用于设置定时器

    setTimeout(function,delay);//设置延时多少毫秒执行该函数,只执行一次,返回值是一个id
    setInterval(function,delay);//设置间隔多少毫米一直执行该函数,执行多次,返回值是一个id

    两者的区别就在于setTimeout方式只执行一次,而setInterval理论可以执行无数次,直到其被取消。

    2、取消定时器
    上面说过,在开启定时器会返回一个id,这个id是用来区别开启的多个定时器。当我们要取消定时器时,可以使用一下这两个方法。

    clearTimeout(id);取消由setTimeout方式开启的定时器
    clearInterval(id);取消由setInterval方式开启的定时器

    3、循环调用setTimeout
    在使用中,可以用setTimeout方式来实现setInterval的效果,其实这个让我想起了当初学Android是的Handler机制,发一个延时消息,然后在内容中再发出消息。例如:

    <script>
        var t = 1;
        function time(){
            console.log(t++);
            window.setTimeout('time()',1000);
        }
        window.setTimeout('time()',1000);
    </script>

    4、倒计时案例
    在页面上有一个按钮,显示的是倒计时的数字,每隔一秒修改数字,等到0秒时,就切换爆炸图片。

    效果图
    这里写图片描述
    这里写图片描述

    代码

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title></title>
        <link rel="stylesheet" href="">
    </head>
    <body>
        <h1>炸弹效果</h1>
        <input type="button" value="5" /><br/>
        <img src="warn.jpg"/>
    </body>
    <script>
        //定时执行
        function time(){
            var input = document.getElementsByTagName('input')[0];//获取按钮中的数字
            var time = parseInt(input.value) - 1;
            input.value = time;
            //爆炸操作
            if(time <= 0){
                var img = document.getElementsByTagName('img')[0];
                img.src = 'boom.jpg';//切换爆照图片
                clearInterval(t1);//清除定时器
            }
        }
        var t1 = window.setInterval('time()',1000);//开启定时器
    </script>
    </html>

    思路
    其实这个例子挺简单的,首先以每隔1秒开启定时器,在定时执行函数中每次获取当前倒计时的数字,然后进行减1操作,最后又赋值到按钮中,当数字小于或等于0秒时,就切换爆炸图片已达到爆炸效果,此时不要忘记取消定时器了。

  • 相关阅读:
    使用CustomValidate自定义验证控件
    C#中金额的大小写转换
    Andriod出错之Unable to build: the file dx.jar was not loaded from the SDK folder!
    VC 编写的打字练习
    机房工作笔记Ping只有单向通
    web服务协同学习笔记(1)
    Dll 学习3 将MDI子窗口封装在DLL中
    机房工作学习文件共享
    Andriod出错之Failed to find an AVD compatible with target 'Android 2.2'
    Andriod出错之wrapper was not properly loaded first
  • 原文地址:https://www.cnblogs.com/cnsec/p/13407076.html
Copyright © 2011-2022 走看看