Home  >  Article  >  Web Front-end  >  Implementation of javascript timer

Implementation of javascript timer

一个新手
一个新手Original
2017-10-16 09:56:311374browse

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>自动增长计时器</title>
<script type="text/javascript">
  var atime;
  function clock(){
    var time=new Date();          
    atime=time.getHours()+":"+time.getMinutes()+":"+time.getSeconds();
    document.getElementById("clock").value = atime;
  }
 setInterval(clock,1000); 
</script>
</head>
<body>
<form>
<input type="text" id="clock" size="50"  style="background:#000;color:#00ff00;width:55px"; />
</form>
</body>
</html>

Effect:

Display the current time and automatically grow

Add a timer for the button (for start and pause)

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>计时器</title>

<script type="text/javascript">
  var num=0;
  var i;
  function startCount(){
    document.getElementById(&#39;count&#39;).value=num;
    num=num+1;
    i=setTimeout("startCount()",1000);
  }
  function stopCount(){
  clearTimeout(i);
  }
</script>
</head>
<body>
  <form>
    <input type="text" id="count" />
    <input type="button" value="Start" onclick="startCount()"/>
    <input type="button" value="Stop"  onclick="stopCount()" />
  </form>
</body>
</html>

Effect:

#Click the start button to count from 0 and add 1 every second. Click the button to stop and maintain the current state.

Summary:

1. setInterval(code, interaction time);

Parameters: code: can be a function name or code string; interaction time: set the interaction time

clearInterval(id_from_setInterval);

Parameter: ID value returned by setInterval().

2. setTimeout (code, delay time);

Parameters: code: can be a function name or code string; delay time: set the delay time

clearTimeout (id_from_setTimeout) ;

Parameter: ID value returned by setTimeout().

The above is the detailed content of Implementation of javascript 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