使用按钮启动/停止 setTimeout &防止通过更多点击来更快地计数 [英] Start/stop setTimeout with a button & prevent counting faster with more clicks

查看:37
本文介绍了使用按钮启动/停止 setTimeout &防止通过更多点击来更快地计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 JavaScript 并使用 setTimeout 函数进行计数.这是我的代码...

I am working with JavaScript and I use a setTimeout function in order to count up. Here is my code...

<button id="star">Start</button>
<p id="time">0</p>

var timeEl = 0;

function start() {
    time();
}

function time() {
    setTimeout(function() {
        timeEl = timeEl + .1;
        timeEnd = timeEl.toFixed(1);
        document.getElementById("time").innerHTML = timeEnd;
        time();
    }, 100);
}

var el = document.getElementById("star");
el.addEventListener("click", star, false);

  1. 如何在单击按钮时让我的 setTimeout 函数在停止时启动

  1. How do I get my setTimeout function to start on stop when I click on the button

如何防止我点击按钮的次数越多计数越快.

How to prevent my counting from going faster the more times I click on the button.

我在下面包含了我的 JSFiddle!https://jsfiddle.net/pb4759jh68/0618eLoe/

I have included my JSFiddle below! https://jsfiddle.net/pb4759jh68/0618eLoe/

推荐答案

要停止计时器,您可以使用 clearTimeout(),但它确实需要使用 setTimeout 创建的计时器的 ID().对 setTimeout() 的调用现在将计时器 ID 保存在 timeOut 中,然后在 start() 中检查 timeOut 的内容代码> 查看计时器当前是否正在运行.如果计时器正在运行,则在 clearTimeout(timeOut); 中使用 timeOut.

To stop a timer you can use clearTimeout(), but it does require the id of the timer created with setTimeout(). The call to setTimeout() now saves the timer id in timeOut and then checks the contents of timeOut in start() to see whether a timer is currently running. If a timer is running then timeOut is used in clearTimeout(timeOut);.

var timeEl = 0;
var timeOut = null;
function start()
{
  if(timeOut !== null){
    clearTimeout(timeOut);
    timeOut = null;
  }else{
    time();
  }
}
function time()
{
  timeOut = setTimeout(function()
  {
    timeEl = timeEl + .1;
    timeEnd = timeEl.toFixed(1);
    document.getElementById("time").innerHTML = timeEnd;
    time();
  }, 100);
}

var el = document.getElementById("star");
el.addEventListener("click", start, false);

我希望这段代码能解决问题

I hope this code clears the issue

JSFiddle

同样可以使用 setInterval 和 clearInterval 来实现.试试这个 JSFiddle

The same can be achieved using setInterval and clearInterval. Try this JSFiddle

这篇关于使用按钮启动/停止 setTimeout &amp;防止通过更多点击来更快地计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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