clearTimeout在setTimeout的递归调用中无法发挥作用,但是在外界利用函数调用cleartimeout可以停止

问题遇到的现象和发生背景

利用js实现动画的过程中发现在setTimeout的递归调用中,利用判断帧数是否完结,来调用clearTimeout函数时,发现调用后递归依然进行,但是,在外界利用点击事件调用clearTimeout的过程中,发现可以实现停止。

问题相关代码,请勿粘贴截图
<!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>
</head>
<body>
    <button onclick='clearTimeout(timer);'>stop</button>
    <button onclick='move()'></button>//有效
    <div id="block"></div>
</body>
</html>

<style>
    #block{
        position: absolute;
        background-color: aqua;
        width: 50px;
        height:50px;
        margin: 0;
        padding: 0;
        left: 100px;
        top:100px
    }
</style>
<script type="text/javascript">
     //动画每秒的帧数
    var fps=24;
    //每一帧的间隔
    var sps=1000/fps;
    //总的移动时间
    var totaltime=3;
    //总共移动距离
    var distance=100;
    //总帧数
    var fs=parseInt(fps*totaltime);
    //每一帧移动的距离
    var step=distance/fs;
    //获取id
    var timer;
    var block=document.getElementById("block");
    function move(){
        if(fs<=0)
        { 
            clearTimeout(timer);//程序依旧运行
            }
        block.style.left=block.offsetLeft+step+'px';
        fs--;
        timer=setTimeout(move, sps); 
    }
    console.log(fs);
    timer=setTimeout(move,sps);
    console.log(1);
</script>

运行结果及报错内容

无报错

我的解答思路和尝试过的方法

尝试未timer赋值nul任然无法停止

我想要达到的结果

为什么在递归调用中无法停止,但是利用外部调用可以?

清除计时器,并不会跳出move函数,所以会继续执行下面的代码移动了对象,最后的代码又重启计时器又执行了move,一直循环下去了不会停止



    function move() {
        if (fs <= 0) {
            clearTimeout(timer);//这里只是清除计时器,并不会跳出move函数,所以会继续执行下面的代码移动了对象,最后的代码又重启计时器又执行了move
            return;//要return阻止下面的代码执行,要么就加个else,下面的代码放到else代码块中
        }
        block.style.left = block.offsetLeft + step + 'px';
        fs--;
        timer = setTimeout(move, sps);
    }

使用setTimeout做动画效果不需要clearTimeout,只需要判断条件不符合后不需要setTimeout继续重启计时器就行,比如下面的


    function move() {
        if (fs > 0) {//符合条件才继续启动计时器
            block.style.left = block.offsetLeft + step + 'px';
            fs--;
            timer = setTimeout(move, sps);
        }
    }

img

改为setInterval方法就不用递归了。

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632