首页 > 其他 > 详细

用setTimeout模拟setInterval的功能

时间:2019-03-12 13:09:19      阅读:421      评论:0      收藏:0      [点我收藏+]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>test定时器</title>

</head>

<body>
    <input type="button" value= "计时" />
    <input type="button" value= "关闭" />
    <input type="button" value="0" />
</body>

</html>
<script>
    var aInput = document.getElementsByTagName('input');
    /*
    var timer =null;
    aInput[0].onclick=function(){
        console.log('关闭');
        timer= setInterval(numFun,1000)
    }
    aInput[1].onclick = function(){
        console.log('关闭');
        clearInterval(timer)
    }


    var num =0;
    function numFun(){
        num++;
        console.log(num)
        aInput[2].value = num;
    }
    */

    // 用setTimeout模拟setInterval的功能 
    var timer2 =null;
    var timerFlag =false;

    function goTimer(){
        // debugger;
        if(!timerFlag){
            return;
        }
        numFun();
        setTimeout(goTimer,1000)
    }


    var num =0;
    function numFun(){
        num++;
        // console.log(num)
        aInput[2].value = num;
    }   

    aInput[0].onclick=function(){
        console.log('开启');
        timerFlag = true;
        goTimer()
    }

    aInput[1].onclick=function(){
        timerFlag =false;
        console.log('关闭');
    }
</script>

用setTimeout模拟setInterval的功能

原文:https://www.cnblogs.com/hyx626/p/10515688.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!