JS 事件延迟执行

JavaScript012

JS 事件延迟执行,第1张

延迟执行,一般是用定时器,定时器有两种,一种是setInterval,另一个是setTimeout。

setInterval,是间隔执行,次数为无限次。

setTimeout,是隔一段时间,执行一次。

setInterval() 方法可按照指定的周期(以毫秒计)来调用函数或计算表达式。

setInterval() 方法会不停地调用函数,直到 clearInterval() 被调用或窗口被关闭。由 setInterval() 返回的 ID 值可用作 clearInterval() 方法的参数。

setTimeout() 和setInterval() 几乎是一样的,仅执行次数不同和单词不同而已。关闭setTimeout() 是用clearTimeout()

下面举一个setInterval的例子,仅供参考:

<style>    

div {width:100px height:100px position:absolute top:50px left:50px background:#ccc}    

</style>    

<script>    

window.onload=function(){    

var oDiv = document.getElementById('div1')    

var nLeft = parseInt(oDiv.currentStyle?oDiv.currentStyle.left:getComputedStyle(oDiv,false).left)    

var timer = setInterval(function(){    //开启定时器,

nLeft++    

document.title=nLeft    

oDiv.style.left=nLeft+'px'    

if(nLeft == 500)    

{    

clearInterval(timer)    //当left值为500时,关闭定时器。

}

    

},30)    

    

}    

</script>    

</head>    

<body>    

<div id="div1"></div>

<html>

<head>

<title>JS时间累加</title>

<script type="text/javascript">

function RunTime()

{

var now = new Date()

//当前时间

var hours = now.getHours()//时

var minutes = now.getMinutes()//分

var seconds = now.getSeconds()//秒

document.getElementById("NowTime").innerHTML = hours+"时"+minutes+"分"+seconds+"秒"

//秒加时

now = new Date(now.getTime() + (1000*parseInt(document.getElementById("Jtime").value)))//这里是关键

var hoursS = now.getHours()//时

var minutesS = now.getMinutes()//分

var secondsS = now.getSeconds()//秒

document.getElementById("oldTime").innerHTML = hoursS+"时"+minutesS+"分"+secondsS+"秒"

}

</script>

<style type="text/css">

.style1

{

width: 133px

}

</style>

</head>

<body onload="javascript:document.all('Jtime').focus()">

<table align="center">

<tr><td class="style1">当前时间:</td><td colspan="2"><label id="NowTime"></label></td></tr>

<tr><td class="style1">加时之后:</td><td colspan="2"><label id="oldTime"></label></td></tr>

<tr><td class="style1">输入加入时间/秒:</td><td><input id="Jtime"/></td><td><button id="BtnTime" name="BtTime" onclick="RunTime()">计算</button></td></tr>

</table>

</body>

</html>