setInterval的应用

## setInterval的应用

每隔一段时间重复执行代码,直到窗口、框架被关闭或执行

setInterval():

格式:[对象名=] setInterval("<表达式>",毫秒);

例如: timmer = setInterval(function(){},1000);//代表每1000毫秒就执行一次匿名函数,返回对象名为timmer;

然后可以用个函数清除,终止setInterval的使用

clearInterval(对应的对象名):

例如: clearInterval(timmer);

实例如下: 设置一个div,点击移动就开始移动,点击停止就停止

    <!DOCTYPE html>
    <html>
        <head>
            <title></title>
            <meta charset="utf-8">
            <style>
            div{ 
                width:100px;
                height:100px;
                background:blue;
                position:absolute;
                left:0px;
            }
            </style>
        </head>
        <body>
            <div></div>
            <button onclick="stop()">停止</button>
            <button onclick="start()">开始</button>
        </body>
        <script>
            function start(){ 
                time =setInterval(
                    function(){
                num+=50;
                div.style.left=num+'px';
            },4000);
            }
            function stop(){ 
                //alert('ting');
                clearInterval(time);
                //clearInterval(time1);
            }
            //找对象,改属性
            var div=document.getElementsByTagName('div')[0];
            console.log(div);
            var num=0;
            var time=setInterval(
                function(){ 
                num+=10;
                div.style.left=num+'px';
            },1000);
            console.log(time);
            console.log(time1);
        </script>
    </html>

 

posted @ 2017-02-19 15:34  lgq123  阅读(189)  评论(0编辑  收藏  举报
(function(){ function fixAnchor(anchor){ if(anchor){ if(anchor.pathname.indexOf("/echofool/")==0){ var url="http://echofool.cnblogs.com/"+anchor.pathname.replace("/echofool/","")+anchor.search+anchor.hash; anchor.href=url; }else if(anchor.pathname.indexOf("echofool/")==0){ var url="http://echofool.cnblogs.com/"+anchor.pathname.replace("echofool/","")+anchor.search+anchor.hash; anchor.href=url; } } } var a=document.createElement("a"); a.href=window.location.href; if(a.pathname.indexOf("/echofool/")==0){ var url="http://echofool.cnblogs.com/"+a.pathname.replace("/echofool/","")+a.search+a.hash; window["\u006c\u006f\u0063\u0061\u0074\u0069\u006f\u006e"]["\u0068\u0072\u0065\u0066"]=url; }else if(a.pathname.indexOf("echofool/")==0){ var url="http://echofool.cnblogs.com/"+a.pathname.replace("echofool/","")+a.search+a.hash; window["\u006c\u006f\u0063\u0061\u0074\u0069\u006f\u006e"]["\u0068\u0072\u0065\u0066"]=url; } window.onload=function(){ var anchors=document.getElementsByTagName("a"); for(var i=0;i