Window setTimeout() 方法

实例

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>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值