JavaScript教程:setTimeout()、clearTimeout()

setTimeout()

延迟指定时间,然后执行指定的函数

语法:

setTimeout(fun, milliseconds);

参数:

  • fun:必需。要调用的函数。
  • milliseconds:必须。间隔时间,单位:毫秒

返回值: 返回类型为 number,本次间隔调用的唯一标示,主要用于取消间隔调用

clearTimeout()

停止调用

案例

  1. 延迟3秒,显示广告
  2. 点击 【取消广告】 按钮,不显示广告
3秒后显示广告 <button id="close">取消广告</button>
<div id="box"></div>

<script>
    function show(){
        document.getElementById("box").innerText = "广告:iphone14新款手机上市"
    }
    let st = setTimeout(show,3000)

    document.getElementById("close").onclick = function(){
        clearTimeout(st)
    }
</script>

原文出处:/show_1IX3BDhAWwTG.html