Home  >  Article  >  Web Front-end  >  JS implements timer

JS implements timer

小云云
小云云Original
2018-03-27 17:26:111491browse

This article mainly shares with you JS implementation of timer, mainly in the form of code, hoping to help everyone.

Problem description: Execute an event regularly

Mainly solve the problem of restarting

html

<body>
    <button id="btn1">start</button>
    <button id="btn2">stop</button>
</body>

script

<script>
window.addEventListener(&#39;load&#39;, my_timer, false);

function my_timer() {
    let start = document.getElementById("btn1");
    let stop = document.getElementById("btn2");
    //计时函数
    let timer = null;
    let eleClock = function () {
        timer = setInterval(
            function () {
                console.log(new Date())
            },
            1000
        );
    };
    //点击start按钮,开始定时器
    start.onclick = function () {
        //do something
        eleClock();
    };

    //点击stop按钮,停止定时器
    stop.addEventListener(&#39;click&#39;, function () {
        //do something
        window.clearInterval(timer);
    }, false);
}
</script>

Related recommendations:

JS implementation of animation timer method

Detailed explanation of JavaScript timer

##In-depth JavaScript Timer

The above is the detailed content of JS implements timer. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn