淺談setInterval和setTimeout的區別和使用
阿新 • • 發佈:2021-02-02
技術標籤:定時器setTimeoutsetIntervaljavascript
淺談setInterval和setTimeout的區別和使用
1.setlnterval()
setInterval() 方法可按照指定的週期(以毫秒計)來呼叫函式或計算表示式。
autoPlay () {
this.mark++
if (this.mark > this.banner.length - 1) {
// 當遍歷到最後一張圖片置零
this.mark = 0
}
},
play () {
// 每2.5s自動切換
this.timer = setInterval(this.autoPlay, 2500)
},
setInterval() 方法會不停地呼叫函式,直到 clearInterval() 被呼叫或視窗被關閉。由 setInterval() 返回的 ID 值可用作 clearInterval() 方法的引數。
// An highlighted block
startTimer () {
this.timer = setInterval(this.autoPlay, 2500)
},
stopTimer () {
clearInterval(this.timer)
},
2.setTimeout()
setTimeout只在指定時間後執行一次,程式碼如下:
setTimeout() 方法用於在指定的毫秒數後呼叫函式或計算表示式。
// An highlighted block
<html>
<head>
<script type="text/javascript">
//點選button按鈕,隔5秒之後輸出111111
function autoPlay ()
{
var t=setTimeout("alert('1111111')",5000)
}
</script>
</head>
<body>
<form>
<input type="button" value="按鈕" onClick="autoplay()">
</form>
</body>
</html>