定时器/setTimeout()/setInterval()

1.setTimeout(code,time), 超时调用,code表示要执行的代码,time表示延迟的毫秒数

//写法一:
setTimeout("alert('hello')",2000); //表示2秒后执行弹框

//写法二:

function box(){
     alert('hello');            
}
setTimeout(box,2000);

//写法三:

setTimeout(function(){
    alert("hello")    
},2000);

//取消
var st=setTimeout(function(){
    alert("hello")    
},2000);

clearTimeout(st);  //上面的setTimeout()方法就不执行

 

2.setInterval(); 间歇调用,用法与setTimeout()相似,毫秒数表示每隔n毫秒执行一次代码

 

3.倒计时示例

<body>
        //倒计时
        
        <div id="nowT"></div>
    <script>
        
        var cutDown=setInterval(function(){
            var nowT=document.getElementById('nowT');
            var time1=new Date('1/1/2018');
            var time2=new Date();
            var time3=time1.getTime()-time2.getTime();
            var arr=["星期日",'星期一','星期二','星期三','星期四','星期五','星期六'];

            var day=time3/3600/1000/24;
            var hour=time3/3600/1000; 
            var minute=time3/1000/60;
            var second=time3/1000;
            
            
            nowT.innerHTML='距离2018元旦狂欢还有:'+parseInt(day)+''+parseInt(hour%24)+
            '小时'+parseInt(minute%60)+''+parseInt(second%60)+''+'<br/>'+'today:'+arr[time2.getDay()];
        },500);
    </script>
    
  </body>

 

posted @ 2017-03-20 14:08  Hailinlu  阅读(202)  评论(0编辑  收藏  举报