setInterval(),能夠讓你重複的執行一個函數,要做動畫也可以只要確保你的偵數即下次重複的時間要小於50ms,讓眼睛能達到視覺的暫留即可。
使用方法
<script>
setInterval(function, 10)//能夠啟用但你會無法停止
var intervalID=setInterval(function_name, 10)//正常的使用方法,不帶變數直接打函數的名稱即可
//帶變數
//方法一
var intervalID=setInterval(function(){function_name(1000,"你好")}, 10)
//方法二
var intervalID = setInterval(function_name, 1000, 1000, "你好")//秒數後面接的是你帶入的資料
clearInterval(intervalID);//停止
</script>
至於怎麼打,我個人覺得方法一可讀性比較高,會比較偏向用這打法就是了
<body>
<div class="d-flex justify-content-center w-100 flex-wrap">
<label class="text-center w-100 mt-5">時間:<span id="times">00:00:00</span></label>
<button type="button " class="btn-info mt-3 p-3" id="time_btn">開始</button>
</div>
</body>
<script>
var button = document.getElementById("time_btn")
var ms = 0,s = 0,m = 0
var start = false
var time_GO
var intervalID = setInterval(function_name, 1000, 1000)
function function_name(number1, number2) {
console.log(number1, number2)
}
button.addEventListener("click", function () {
start = !start
button.innerHTML = button.innerHTML === "繼續" ? "停止" : "繼續"
if (start) {
time_GO = setInterval(function () {
time_go()
}, 10)
} else {
clearInterval(time_GO)
}
})
//計時部分
function time_go() {
ms += 1
if (ms == 100) {
ms = 0
s += 1
}
if (s == 60) {
s = 0
m += 1
}
if (m == 60) {
m = 0
}
let timetext = ""
if (m <= 9) {
timetext = "0" + m
} else {
timetext += ":" + m
}
if (s <= 9) {
timetext += ":0" + s
} else {
timetext += ":" + s
}
if (ms <= 9) {
timetext += ":0" + ms
} else {
timetext += ":" + ms
}
var times = document.getElementById("times")
times.innerHTML = timetext
}
</script>
簡單來說就是這樣使用,還可以用來定時變換圖片,背景顏色,物件顏色等等,又或是自動轉場
今天就這樣啦~~