Home > Web Front-end > JS Tutorial > body text

How to implement counter basics in JavaScript

黄舟
Release: 2017-10-11 10:18:29
Original
3422 people have browsed it

This article mainly introduces in detail the basic method of implementing counters in JavaScript. , has a certain reference value, interested friends can refer to it

The example of this article shares the specific code of js implementation counter for your reference, the specific content is as follows

By using JavaScript executes code after a set interval, rather than immediately after the function is called. Call it a timing event.

It is very easy to use timing events in JavaScript. The two key methods are:

setInterval() - execute the specified event continuously for the specified number of milliseconds. code.
setTimeout() - Execute the specified code after pausing for the specified number of milliseconds

Note: setInterval() and setTimeout() are two methods of the HTML DOM Window object. Only the setTimeout() method is introduced here;


<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8">
    <script type="text/javascript">
      var c = 0
      var t

      function timedCount() {
        document.getElementById(&#39;txt&#39;).value = c;
        c = c + 1;
        //创建计时器,在指定周期内循环执行
        t = setTimeout("timedCount()", 1000);
      }

      function stopCount() {
        //清除计时器
        clearTimeout(t);
      }
    </script>
  </head>

  <body>

    <form>
      <input type="button" value="开始计时!" onClick="timedCount()">
      <input type="text" id="txt">
      <input type="button" value="停止计时!" onClick="stopCount()">
    </form>



  </body>

</html>
Copy after login

Effect:

Click start and it will Start counting from 0. If you stop the timing, it will pause at that moment. If you click start again, the counting will continue... But there is a small bug in this program. When you keep clicking to start timing, the timing speed will increase, and click once. Stopping the timer will not stop, it will take many responding clicks to stop...

The above is the detailed content of How to implement counter basics in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!