一个简单的 JavaScript 倒数计时器的代码? [英] Code for a simple JavaScript countdown timer?

查看:26
本文介绍了一个简单的 JavaScript 倒数计时器的代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用一个简单的倒数计时器,从函数运行时的 30 秒开始,到 0 结束.没有毫秒.如何编码?

I want to use a simple countdown timer starting at 30 seconds from when the function is run and ending at 0. No milliseconds. How can it be coded?

推荐答案

var count=30;

var counter=setInterval(timer, 1000); //1000 will  run it every 1 second

function timer()
{
  count=count-1;
  if (count <= 0)
  {
     clearInterval(counter);
     //counter ended, do something here
     return;
  }

  //Do code for showing the number of seconds here
}

要使计时器的代码出现在段落中(或页面上的任何其他位置),只需输入以下行:

To make the code for the timer appear in a paragraph (or anywhere else on the page), just put the line:

<span id="timer"></span>

您希望秒数出现的位置.然后在您的 timer() 函数中插入以下行,如下所示:

where you want the seconds to appear. Then insert the following line in your timer() function, so it looks like this:

function timer()
{
  count=count-1;
  if (count <= 0)
  {
     clearInterval(counter);
     return;
  }

 document.getElementById("timer").innerHTML=count + " secs"; // watch for spelling
}

这篇关于一个简单的 JavaScript 倒数计时器的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆