实例
3 秒(3000 毫秒)后弹出 "Hello" :
setTimeout(function(){ alert("Hello"); }, 3000);
实例
在第 2、4、6 秒修改输入框中的文本:
var x = document.getElementById("txt"); setTimeout(function(){ x.value = "2 秒" }, 2000); setTimeout(function(){ x.value = "4 秒" }, 4000); setTimeout(function(){ x.value = "6 秒" }, 6000);
实例
使用 clearTimeout() 来阻止函数的执行:
var myVar; function myFunction() { myVar = setTimeout(function(){ alert("Hello") }, 3000); } function myStopFunction() { clearTimeout(myVar); }
实例
<button οnclick="openWin()">打开 "窗口"</button>
<script>
function openWin() {
var myWindow = window.open("", "", "width=200, height=100");
myWindow.document.write("<p>这是一个新窗口'</p>");
setTimeout(function(){ myWindow.close() }, 3000);
}
</script>
实例
<p>点击按钮,等待 3 秒后弹出 "Hello" 。</p>
<p>点击第二个按钮来阻止弹出函数 myFunction 的执行。 (你必须在 3 秒前点击)</p>
<button οnclick="myFunction()">先点我</button>
<button οnclick="myStopFunction()">阻止弹出</button>
<script>
var myVar;
function myFunction() {
myVar = setTimeout(function(){ alert("Hello") }, 3000);
}
function myStopFunction() {
clearTimeout(myVar);
}
</script>
实例
<button οnclick="startCount()">开始计数!</button>
<input type="text" id="txt">
<button οnclick="stopCount()">停止计数!</button>
<p>
点击 "开始计数!" 按钮开始执行计数程序。输入框从 0 开始计算。 点击 "停止计数!" 按钮停止后,可以再次点击点击 "开始计数!" 按钮会重新开始计数。
</p>
<script>
var c = 0;
var t;
var timer_is_on = 0;
function timedCount() {
document.getElementById("txt").value = c;
c = c + 1;
t = setTimeout(function(){ timedCount() }, 1000);
}
function startCount() {
if (!timer_is_on) {
timer_is_on = 1;
timedCount();
}
}
function stopCount() {
clearTimeout(t);
timer_is_on = 0;
}
</script>
实例
<body οnlοad="startTime()">
<div id="txt"></div>
<script>
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
// 在 numbers<10 的数字前加上 0
m = checkTime(m);
s = checkTime(s);
document.getElementById("txt").innerHTML = h + ":" + m + ":" + s;
var t = setTimeout(function(){ startTime() }, 500);
}
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
</script>
</body>