本篇文章主要介紹了js中定時器的使用方法。需要的朋友可以過來參考下,希望對大家有所幫助
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> 代碼如下: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> <script language="javascript" type="text/javascript"> var YC = new Object(); function beginYC() { var secondsYC = document.getElementById("txtYCSeconds").value; try { YC = setTimeout("alert('延遲"+secondsYC+"秒成功')",secondsYC*1000); } catch(e) { alert("請輸入正確的秒數。"); } } function overYC() { clearTimeout(YC); YC=null; alert("終止延遲成功。"); } /**************************↓↓↓↓定時器的使用↓↓↓↓********************************/ var timerDS = new Object(); var timerDDS = new Object(); function beginDS() { sn.innerHTML = "0"; timerDS = setInterval("addOne()",parseInt(document.getElementById("txtIntervalSeconds").value,10)*1000); } function goonDS() { timerDS = setInterval("addOne()",parseInt(document.getElementById("txtIntervalSeconds").value,10)*1000); } function overDS() { clearInterval(timerDS); timerDS=null; } function delayDS() { overDS(); timerDDS = setTimeout("goonDS()",document.getElementById("txtDDSSeconds").value*1000); } function addOne() { if(sn.innerHTML=="10") { overDS(); alert("恭喜你,已成功達到10秒"); return; } sn.innerHTML=parseInt(sn.innerHTML,10)+1; } </script> </head> <body> <form id="form1" runat="server"> <div> 延遲器的使用:</div> <div> <label id="Label2" title="延遲秒數:"></label> <input type="text" id="txtYCSeconds" value="3" /> <input type="button" id="btnBYC" onclick="javascript:beginYC()" value="開始延遲" /> <input type="button" id="btnOYC" onclick="javascript:overYC()" value="終止延遲" /> <input type="button" id="Button1" onclick="javascript:alert('good monrning');" value="普通彈窗" /> </div> <br /> <div> 定時器的使用:</div> <div> <div id="sn">0</div> <label id="Label1" title="定時間隔秒數:"></label> <input type="text" id="txtIntervalSeconds" value="1" /> <input type="button" id="btnBDS" onclick="javascript:beginDS()" value="啟動定時" /> <input type="button" id="btnODS" onclick="javascript:overDS()" value="終止定時" /> <input type="button" id="btnGDS" onclick="javascript:goonDS()" value="繼續定時" /> <label id="ds" title="延遲秒數:"></label> <input type="text" id="txtDDSSeconds" value="5" /> <input type="button" id="btnDDS" onclick="javascript:delayDS()" value="延遲定時" /> </div> </form> </body> </html>