JS定時器用法分析【時鐘與菜單中的應用】,js定時器

來源:互聯網
上載者:User

JS定時器用法分析【時鐘與菜單中的應用】,js定時器

本文執行個體分析了JS定時器用法。分享給大家供大家參考,具體如下:

開啟定時器:

setInterval 間隔型    //一旦啟動就不會停,重複執行
setTimeout 延遲型   //只執行一次

停止定時器:

clearInterval
clearTimeout

關閉定時器如果只是clearInterval()那會關掉所有的定時器,有時我們只需要關掉一個而已,所以要定義一個變數來存放定時器

var timer=null;btn1.onclick=function(){  timer=setInterval(函數名,1000);};btn2.onclick=function(){  clearInterval(timer);};

例子1

時刻變化的時鐘,且數字是由圖片代替的

思路:

1.建立Date(日期)對象,擷取系統時間(注:擷取時間如果是一位元,需要一個轉換成二位元的函數)

2.將獲得的系統時間每一位元字賦給圖片地址的數字編號(charAt()方法,返回字串指定位置的字元,所以需要一個for迴圈返回時分秒六位元字)

3.需要一個定時器讓它自動更新時間

function toDouble(num){ //一位元轉換成二位元  if(num<10){    return '0'+num;  }else{    return ''+num;  }}window.onload=function(){  var oimg=document.getElementsByTagName('img');  var i;  function updatetime(){    var odate=new Date();    var str=toDouble(odate.getHours())+toDouble(odate.getMinutes())+toDouble(odate.getSeconds());    for(i=0;i<oimg.length;i++){      oimg[i].src='images/'+str.charAt(i)+'.png';    }  }  setInterval(updatetime,1000); //定時器裡面應該放的是方法,而不是直接執行函數  updatetime(); //不執行下函數,會出現剛重新整理頁面第一秒,時間是00時00分00秒}

例子2

二級菜單

一級菜單和二級菜單間有縫隙,如果僅僅是移入一級菜單時二級顯示,移除時隱藏,那麼移到縫隙間還是會顯示不出來(或者說來不及進入二級菜單,二級菜單就沒了),所以需要一個定時器,在離開一級菜單時,不讓二級馬上消失,而是緩慢隱藏,然後在進入二級菜單時,清除這個定時器,他就不會消失了,另外離開二級菜單時,還是要讓它消失,不然會永遠存在

window.onload=function(){  var box1=document.getElementById('box1');  var box2=document.getElementById('box2');  var timer=null;  box1.onmouseover=function(){    box2.style.display="block";    clearTimeout(timer);  //不清除定時器,離開二級菜單進入一級菜單時,二級菜單也會隱藏  };  box1.onmouseout=function(){    timer=setTimeout(function(){      box2.style.display="none";    },300);  };  box2.onmouseover=function(){    clearTimeout(timer);  };  box2.onmouseout=function(){  //如果離開二級菜單,讓他瞬間消失,IE7下移動到一級菜單時,二級菜單會閃爍    timer=setTimeout(function(){      box2.style.display="none";    },300);  };};

簡化下代碼

window.onload=function(){  var box1=document.getElementById('box1');  var box2=document.getElementById('box2');  var timer=null;  box1.onmouseover=box2.onmouseover=function show(){    box2.style.display="block";    clearTimeout(timer);  };  box1.onmouseout=box2.onmouseout=function hide(){    timer=setTimeout(function(){      box2.style.display="none";    },300);  };};

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.