简体   繁体   English

javaScript中的计时器不起作用

[英]Timer in javaScript doesnt work

I am making a simple timer in javaScript which starts when you click anywhere in the document and it resets on clicking again. 我在javaScript中创建了一个简单的计时器,该计时器在您单击文档中的任何位置时启动,并在再次单击时重置。

var k = 0,
  m = 0,
  s = 0;
document.onclick =
  function() {
    k = 0;
    setTimeout(function() {
      k++;

      if (Math.floor(k / 6000) > 1) {
        m = Math.floor(k / 6000);
        s = Math.floor(k % 6000);
      } else
        s = Math.floor(k / 100);
      document.getElementById('input3').value = "0" + m + ":" + "0" + s + "  " + k;
    }, 10);
  };

input3 is the id of textbox in html in timer in which countdown is displayed input3是计时器中html中文本框的ID,其中显示倒计时

What you probably want is setInterval instead of setTimeout . 您可能想要的是setInterval而不是setTimeout

I made this example that sounds like what you want. 我做了这个例子,听起来像您想要的。 https://jsfiddle.net/5yke1hmp/ https://jsfiddle.net/5yke1hmp/

setTimeout(function() { is the problem, if you want to create a timer you should use setInterval(function() { setTimeout(function() {是问题,如果要创建计时器,则应使用setInterval(function() {

setInterval will execute the function after every ''specified time' while setTimeout will only run the function once after 'specified time' setInterval将在每个“指定时间”之后执行该函数,而setTimeout将仅在“指定时间”之后运行该函数一次

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM