JavaScript定时器

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>定时器</title>
</head>
<body>
    <button id = "start">开始</button>
    <button id = "end">结束</button>

<script>

    let startBtn = document.querySelector("#start");
    let endBtn = document.querySelector("#end");
    let id = null;
    startBtn.onclick = function() {
        // 重复执行的定时器
        id = setInterval(function () {
            console.log("Hello World!");
        }, 1000);
    };
    endBtn.onclick = function() {
        // 终止定时器
        clearInterval(id);
    };
</script>
</body>
</html>

原文地址:https://www.cnblogs.com/TomHe789/p/12656804.html