Home  >  Article  >  Web Front-end  >  Timers in Javascript

Timers in Javascript

autoload
autoloadOriginal
2021-04-12 15:57:532381browse

Timers in Javascript

There are two timers in Javascript, namely setInterval() and setTimeout(), both Both are timers, but they are different. This article will take you to understand these two timers.

1.setTimeout()

Set timer

 <script>
        setTimeout(setTime,2000);
        function setTime(){
             alert("2秒时间到了");
        }

    </script>

Clear timer

<body>
    <button>按钮2</button>
    <script>
        const btn=document.querySelector("button");
        let set=setTimeout(() => {
            alert("已经过去三秒了");
        }, 3000);
        btn.addEventListener("click",(e)=>{
            clearTimeout(set);
        });

      
    </script>
</body>

2.setInterval()

Set the timer

<script>
        setInterval(setInter, 3000);
        function setInter(){
             console.log("我被周期性3s时间打印");
        }
    </script>

Clear the timer

<body>
    <button>按钮1</button>
    <script>
        const btn=document.querySelector("button");
        let set=setInterval(setInter, 3000);
        btn.onclick=(e)=>{
            clearInterval(set);
        };
        function setInter(){
             console.log("我被周期性3s时间打印");
        }
    </script>
</body>

Recommended: "2021 js interview questions and answers (large summary)"

The above is the detailed content of Timers in Javascript. 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