定时器的回调函数

setTimeout()这个调用函数我们也称为回调函数callback

普通函数是按照代码顺序直接调用。

而这个函数,需要等待时间,时间到了才去调用这个函数,因此称为回调函数。

简单理解︰回调,就是回头调用的意思。上一件事千完,再回头再调用这个函数。

以前我们讲的element.onclick=function(或者element.addEventListener("click",fn);里面的函数也是回调函数。

案例:几秒之后关闭广告:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .ad {
            height: 300px;
        }
    </style>
</head>

<body>
    <img src="img/333.jpg" class="ad" alt="">
</body>
<script>
    var ad = document.querySelector('.ad');
    setTimeout(function () {
        ad.style.display = 'none'
    }, 2000)
</script>

</html>

 

posted @ 2022-04-12 13:30  今天穿秋裤了吗  阅读(691)  评论(0)    收藏  举报