zoukankan      html  css  js  c++  java
  • 14-----定时器

    在js中的定时器分两种:1、setTimeout()    2、setInterval()

    1、setTimeOut()

    只在指定时间后执行一次

    /定时器 异步运行  
    function hello(){  
    alert("hello");  
    }  
    //使用方法名字执行方法  
    var t1 = window.setTimeout(hello,1000);  
    var t2 = window.setTimeout("hello()",3000);//使用字符串执行方法  
    window.clearTimeout(t1);//去掉定时器
    //等待2秒之后 fn会去执行 fn我们称为叫回调函数
            setTimeout(function() {
                // body...
                console.log(2222);
            }, 2000);
    
            console.log(1111);

    2、setInterval()

     在指定时间为周期循环执行

    /实时刷新  时间单位为毫秒  
    setInterval('refreshQuery()',8000);   
    /* 刷新查询 */  
    function refreshQuery(){  
      console.log('每8秒调一次') 
    }
        var a = 0 ;
        setInterval(function(){
            a++;
            console.log(a);
        },300)   

    刷盒子移动

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
    <div id="box" style=" 100px;height: 100px;background-color: red;">
    </div>
    
    <script>
    
        var a = 0 ;
        var oDiv = document.getElementById('box');
        setInterval(function(){
            a++;   //a+=3
            oDiv.style.marginLeft = a+'px';
            console.log(a)
        },300);    //每300毫秒
        
    </script>
    </body>
    </html>

    清除定时器

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
    <div id="box" style=" 100px;height: 100px;background-color: red;">
    </div>
        <button id="btn">停止</button>
    <script>
            var a = 0;
            function $(id){
                return document.getElementById(id);
            }
    
            var c = setInterval(function() {
                // body...
                a+=3;
                $('box').style.marginLeft = a+'px';
                console.log(a);
            },50);
    
            $('btn').onclick = function(){
                clearInterval(c);
            };
    
    //
    //        //等待2秒之后 fn会去执行 fn我们称为叫回调函数
    //        setTimeout(function() {
    //            // body...
    //            console.log(2222);
    //        }, 2000);
    //
    //        console.log(1111);
    
    </script>
    </body>
    </html>

    两种方法根据不同的场景和业务需求择而取之,

    对于这两个方法,需要注意的是如果要求在每隔一个固定的时间间隔后就精确地执行某动作,那么最好使用setInterval,而如果不想由于连续调用产生互相干扰的问题,尤其是每次函数的调用需要繁重的计算以及很长的处理时间,那么最好使用setTimeout

  • 相关阅读:
    Yaf 在 Nginx 中的配置
    关于 GPG 用这个 就够 了
    PHP 服务器端处理跨域问题
    Linux 终端代理方式
    【转载】Oracle数据字典详解
    【转载】Oracle之内存结构(SGA、PGA)
    【转载】 使用rman进行坏块修复(ORA-01578、ORA-01110)
    【转载】使用Exp和Expdp导出数据的性能对比与优化
    【转载】oracle dbms_metadata.get_ddl的使用方法总结
    ORACLE执行详解
  • 原文地址:https://www.cnblogs.com/edeny/p/9288621.html
Copyright © 2011-2022 走看看