Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
507 views
in Technique[技术] by (71.8m points)

为什么清除不掉定时器?clearTimeout不生效


    <div style="height: 50px;width:50px;margin:60px auto;background:green;" onmouseover="cancelInterval()" onmouseout="intervalFun()">
        blockA
    </div>
    <div style="height: 50px;width:50px;margin:60px auto;background:palegreen;" onclick="reStart()">
        blockB
    </div>

<script>
    let timeout = null;
    let a = 1;

    function intervalFun() {
        timeout = setTimeout(function () {
            console.log(1);
            setTimeout(intervalFun, 1000);
        }, 1000);
    }

    function cancelInterval() {
        console.log(timeout);
        clearTimeout(timeout);
    }

    function reStart() {
        cancelInterval();
        intervalFun();
    }

    intervalFun();
</script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
let timeout = null;
let a = 1;
function intervalFun() {
  clearTimeout(timeout);
  timeout = setTimeout(function () {
    console.log(1);
    intervalFun()
  }, 1000);
}

function cancelInterval() {
  console.log(timeout);
  clearTimeout(timeout);
}
function reStart(){
  cancelInterval();
  intervalFun();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...