定时器
以毫秒的计算 定时器setTimeout( )
<script> // 以毫秒的计算 定时器setTimeout( ) // 第一种方法 setTimeout(function () { console.log("三秒钟到了"); }, 3000); </script>
<script> // 第二种方法 function adc() { console.log("爆炸了"); } setTimeout(adc, 3000); </script>
点击按钮停止定时: clearTimeout()
<body> <button>停止</button> <img src="/img/images/4.jpg" alt="" /> </body> <script> var ad = document.querySelector("img"); var at = setTimeout(function () { ad.style.display = "none"; }, 4000); var btn = document.querySelector("button"); btn.addEventListener("click", function () { clearTimeout(at); //停止定时器(需要停止的定时器的名字) }); </script>
回调函数以及5秒之后自动关闭的广告 :
setTimeout( ) 这个函数我们也称为回调函数callback
普通函数是按照代码顺序直接调用的
而这个函数,需要的等待时间,时间到了才去调用这个函数,因此也称为回调函数
简单理解:回调就是回头调用的意思。上一件事干完,再回头在调用这个函数
<body>
<img src="/img/images/3.jpg" alt="" />
</body>
<script>
var ad = document.querySelector("img");
setTimeout(function () {
ad.style.display = "none";
}, 2000);
</script>