关于清除定时器的问题,setTimeout

如下代码,用setInterval自然是没问题,因为使用都是同一个timer,请问setTimeout怎么解决这个问题?

        function scrollbars(){
            index++;
            if(index <= max){
                target = index * singleHeight;
            }else{
                index = 0;
                target = index * singleHeight;
            }

            $el.animate({'top': target}, 1000, function(){
                timer = setTimeout(scrollbars, 2000);
            });
        }

        timer = setTimeout(scrollbars, 2000);

        $('#container').on('mouseenter', function(){
            //    这里鼠标移入,清除定时器,可能在清除之前,上面已经生成新的定时器了,所以只是清除了之前的定时器,这里可能无法起到停止的作用
            clearTimeout(timer);
        });
阅读 12.1k
3 个回答

申请一个指示作用的变量,没有为0,有为1,然后在settime里加判断,其实这样做的话,你连清除也不用做了。

// 添加
timerPool = []
timerPool.push(setTimeout(.....))
timerPool.push(setTimeout(.....))
// 清除
timerPool.forEach((timer) => {clearTimeout(timer)})

好像问题是不是在清除之前又生成了新的定时器,而是在animate过程中,你清除了定时器,而动画结束后又生成了新的定时器。
所以试试在mouseenter的回调函数里加个stop=true,然后在animate的回调里根据这个stop判断是否还继续setTimeout,这个办法可行不可行。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题