我正在研究一個網頁,它將顯示來自網絡攝像頭的靜止圖像,因此需要每15秒刷新一次。如何自動啓動JavaScript倒數計時器
我想實現一個倒數計時器到我的頁面來顯示頁面將刷新。
我在W3schools.com上發現了這個代碼,並且改變了它以適合我的需要,但是這個倒數計時器只會在用戶按下啓動按鈕後纔會啓動。我想知道如何更改腳本以使計時器在頁面加載時自動啓動?
下面是代碼:
<!DOCTYPE html>
<html>
<head>
<body>
<script>
function timedText() {
var x = document.getElementById('txt');
var t1 = setTimeout(function(){x.value = "15 seconds"},1000);
var t2 = setTimeout(function(){x.value = "14 seconds"},2000);
var t3 = setTimeout(function(){x.value = "13 seconds"},3000);
var t4 = setTimeout(function(){x.value = "12 seconds"},4000);
var t5 = setTimeout(function(){x.value = "11 seconds"},5000);
var t6 = setTimeout(function(){x.value = "10 seconds"},6000);
var t7 = setTimeout(function(){x.value = "9 seconds"},7000);
var t8 = setTimeout(function(){x.value = "8 seconds"},8000);
var t9 = setTimeout(function(){x.value = "7 seconds"},9000);
var t10 = setTimeout(function(){x.value = "6 seconds"},10000);
var t11 = setTimeout(function(){x.value = "5 seconds"},11000);
var t12 = setTimeout(function(){x.value = "4 seconds"},12000);
var t13 = setTimeout(function(){x.value = "3 seconds"},13000);
var t14 = setTimeout(function(){x.value = "2 seconds"},14000);
var t15 = setTimeout(function(){x.value = "1 seconds"},15000);
}
</script>
</head>
<body>
<form>
<input type="button" value="start" onclick="timedText()" />
<input type="text" id="txt" />
</form>
</body>
</html>
編輯:這是從我的網頁的原代碼:
<!DOCTYPE html>
<HTML>
<HEAD>
<script type="text/JavaScript">
<!--
function timedRefresh(timeoutPeriod) {
setTimeout("location.reload(true);",timeoutPeriod);
}
// -->
</script>
<TITLE>Local MDOT Cam's-KD8NXH's Page-- Superior Twp., Michigan</TITLE>
<link rel="icon"
type="image/ico"
href="http://www.qsl.net/k/kd8nxh/favicon.ico">
<link rel="shortcut icon" href="http://www.qsl.net/k/kd8nxh/favicon.ico"
type="image/icon"> <link rel="icon" href="http://www.qsl.net/k/kd8nxh/favicon.ico" type="image/icon">
</head>
<body onload="JavaScript:timedRefresh(15000); timedText()">
<a href="http://www.qsl.net/kd8nxh/";"><img alt="" src="http://www.qsl.net/kd8nxh/BlueHomeButton.gif" style="width: 100px; height: 25px;" /></a>
<script>
window.onload = timedText;
function timedText() {
var txt = document.getElementById('txt'),
counter = 15;
var timer = setInterval(function() {
if(counter === 0) return clearInterval(timer);
txt.value = counter + " seconds";
counter--;
}, 1000);
}
請不要使用[* W3Schools *](http://www.w3fools.com)。 – RobG 2014-12-08 02:02:43
^他們很適合快速參考,但不適合「教學」 除此之外,他們提供的這些代碼是糟糕的設計實踐。考慮使用超時聲明的循環。 – ryanlutgen 2014-12-08 02:05:09
@RobG你能推薦一個值得信賴的代碼源嗎? – NoviceCodingGeek 2014-12-08 02:13:27