JavaScript超时调用、间歇调用

超时调用

//onclick设置按钮点击之后要执行的代码地址,fnFun就是要执行的代码函数
<input type="button" value="暂停" onclick="fnFun()">
<script>    
var fnFun2 = function (){
    console.log('fnFun2');
}
//参数一:超时后会被调用的函数地址
//参数二:等待时间
//返回值:定时器的ID,可以通过这个ID来终止这个定时器
var id = setTimeout(fnFun2,5000);

var fnFun = function (){
    console.log('hello');
    //终止这个定时器,参数是定时器ID
    clearTimeout(id);
}
console.log('hello world');
</script>

间歇调用

//setInterval,是每隔一段时间就就会调用函数一次
<input type="button" value="暂停" onclick="fnFun()">
<script>
    var fnFun2 = function (){
        console.log('fnFun2');
    }
    //设置间歇调用,定时器
    var id = setInterval(fnFun2,1000);

    var fnFun = function (){
        console.log('hello');
        //清除定时器
        clearInterval(id);
    }
    console.log('hello world');
</script>
posted @ 2019-12-17 14:23  Lay0us  阅读(203)  评论(0编辑  收藏  举报