JavaScript计时器示例分析

  1.什么是JavaScript计时器?

  在JavaScript中,我们可以在设定的时间间隔之后来执行代码,而不是在函数被调用后立即执行。

  2.计时器类型

  一次性计时器:仅在指定的延迟时间之后触发一次。

  间隔性触发计时器:每隔一定的时间间隔就触发一次

  3.计时器方法

  1):一次性计时器

  A):setTimeout(): 指定的延迟时间之后来执行代码,进执行一次

  语法:setTimeout(代码,延迟时间);

  参数说明:

  1. 要调用的函数或要执行的代码串。

  2. 延时时间:在执行代码前需等待的时间,以毫秒为单位(1s=1000ms)。

  B):clearTimeout():取消setTimeout()设置

  语法:clearTimeout(timer)

  参数说明:

  timer:由 setTimeout() 返回的 ID 值。该值标识要取消的延迟执行代码块。

  调用setTimeout()和clearTimeout()延迟方法:

  

复制代码 代码如下:

  <!DOCTYPE html>

  <html>

  <head>

  <meta charset="utf-8">

  <title>JavaScript计时器</title>

  <input type="button" value="开始" id="btnStart" onclick="StartPrint()">

  <input type="button" value="暂停" id="btnStop" onclick="StopPrint()">

  <br>

  </head>

  <body>

  <script type="text/javascript">

  //定义打印方法

  function Print()

  {

  console.log("我在打印!");

  }

  var timer;//该值标识要取消的延迟执行代码块

  //开始打印

  function StartPrint()

  {

  timer=setTimeout(Print,1000);//调用计时器,延迟1秒打印,只执行一次

  }

  //结束打印

  function StopPrint()

  {

  clearTimeout(timer);//取消计时器

  }

  </script>

  </body>

  </html>

  调用setTimeout()和clearTimeout()无限循环方法:

  

复制代码 代码如下:

  <!DOCTYPE html>

  <html>

  <head>

  <meta charset="utf-8">

  <title>JavaScript计时器</title>

  <input type="button" value="开始" id="btnStart" onclick="StartPrint()">

  <input type="button" value="暂停" id="btnStop" onclick="StopPrint()">

  <br>

  </head>

  <body>

  <script type="text/javascript">

  //定义打印方法

  function Print()

  {

  console.log("我在打印!");

  timer=setTimeout(Print,1000);//开始计时器,调用自己,进行无穷循环

  }

  var timer;//该值表示要取消延迟执行的代码块

  //开始打印

  function StartPrint()

  {

  Print();//调用打印方法

  }

  //结束打印

  function StopPrint()

  {

  clearTimeout(timer);//取消计时器

  }

  </script>

  </body>

  </html>

  2):间隔性触发计时器

  A):setInterval():在执行时,从载入页面后每隔指定的时间执行代码

  语法:setInterval(代码,交互时间);

  参数说明:

  1. 代码:要调用的函数或要执行的代码串。

  2. 交互时间:周期性执行或调用表达式之间的时间间隔,以毫秒计(1s=1000ms)。

  返回值:

  一个可以传递给 clearInterval() 从而取消对"代码"的周期性执行的值。

  调用函数格式(假设有一个clock()函数):

  setInterval("clock()",1000) 或 setInterval(clock,1000)

  B):clearInterval() 方法可取消由 setInterval() 设置的交互时间

  语法:clearInterval(timer)

  参数说明:

  timer:由 setInterval() 返回的 ID 值。

  调用setInterval()和clearInterval() 执行间隔执行方法实例

  

复制代码 代码如下:

  <!DOCTYPE html>

  <html>

  <head>

  <meta charset="utf-8">

  <title>JavaScript计时器</title>

  <input type="button" value="开始" id="btnStart" onclick="StartPrint()">

  <input type="button" value="暂停" id="btnStop" onclick="StopPrint()">

  <br>

  </head>

  <body>

  <script type="text/javascript">

  //定义打印方法

  function Print()

  {

  console.log("我在打印!");

  }

  var timer;//该值标识要取消的计时器执行代码块

  //开始打印

  function StartPrint()

  {

  timer=setInterval("Print()",1000);//开始计时器

  }

  //结束打印

  function StopPrint()

  {

  clearInterval(timer);;//取消计时器

  }

  </script>

  </body>

  </html>

  以上就是本文所述的全部内容了,希望小伙伴们能够喜欢。