如何使用JavaScript创建秒表?

 hero-laiquwuz_82914c 发布于 2023-02-13 15:18

jsbin.com demo

您将看到演示代码只是一个启动/停止/重置毫秒计数器.如果你想在时间上做出奇特的格式,那完全取决于你.这应该足以让你入门.

这是一个有趣的小项目.这就是我接近它的方式

var Stopwatch = function(elem, options) {

  var timer       = createTimer(),
      startButton = createButton("start", start),
      stopButton  = createButton("stop", stop),
      resetButton = createButton("reset", reset),
      offset,
      clock,
      interval;

  // default options
  options = options || {};
  options.delay = options.delay || 1;

  // append elements     
  elem.appendChild(timer);
  elem.appendChild(startButton);
  elem.appendChild(stopButton);
  elem.appendChild(resetButton);

  // initialize
  reset();

  // private functions
  function createTimer() {
    return document.createElement("span");
  }

  function createButton(action, handler) {
    var a = document.createElement("a");
    a.href = "#" + action;
    a.innerHTML = action;
    a.addEventListener("click", function(event) {
      handler();
      event.preventDefault();
    });
    return a;
  }

  function start() {
    if (!interval) {
      offset   = Date.now();
      interval = setInterval(update, options.delay);
    }
  }

  function stop() {
    if (interval) {
      clearInterval(interval);
      interval = null;
    }
  }

  function reset() {
    clock = 0;
    render();
  }

  function update() {
    clock += delta();
    render();
  }

  function render() {
    timer.innerHTML = clock/1000; 
  }

  function delta() {
    var now = Date.now(),
        d   = now - offset;

    offset = now;
    return d;
  }

  // public API
  this.start  = start;
  this.stop   = stop;
  this.reset  = reset;
};

获取一些基本的HTML包装器


用法很简单

var elems = document.getElementsByClassName("stopwatch");

for (var i=0, len=elems.length; i

作为奖励,您还可以获得定时器的可编程API.这是一个用法示例

var elem = document.getElementById("my-stopwatch");
var timer = new Stopwatch(elem, {delay: 10});

// start the timer
timer.start();

// stop the timer
timer.stop();

// reset the timer
timer.reset();

jQuery插件

至于jQuery部分,一旦你有如上所述的良好代码组合,编写一个jQuery插件就是一个简单的模式

(function($) {

  var Stopwatch = function(elem, options) {
    // code from above...
  };

  $.fn.stopwatch = function(options) {
    return this.each(function(idx, elem) {
      new Stopwatch(elem, options);
    });
  };
})(jQuery);

jQuery插件用法

// all elements with class .stopwatch; default delay (1 ms)
$(".stopwatch").stopwatch();

// a specific element with id #my-stopwatch; custom delay (10 ms)
$("#my-stopwatch").stopwatch({delay: 10});

@Tigran如果用户重新启动计算机或刷新浏览器选项卡,计时器也将停止工作.这些不是"陷阱".除非有某种合理的无关要求,否则我不会编写代码来解决这些"问题". (5认同)

哇,很棒的工作.你应该得到500赏金. (4认同)


Legends.. 8

如果您需要微秒精度使用:

performance.now ( - >浏览器支持)

    var t0 = performance.now();
    doSomething();
    var t1 = performance.now();

    console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.");
            
    function doSomething(){    
       for(i=0;i<1000000;i++){var x = i*i;}
    }

与JavaScript可用的其他计时数据(例如Date.now)不同,Performance.now()返回的时间戳不限于1毫秒的分辨率.相反,它们将时间表示为具有高达微秒精度的浮点数.

与Date.now()不同,Performance.now()返回的值总是以恒定速率增加,与系统时钟无关(可以手动调整或由NTP等软件调整).否则,performance.timing.navigationStart + performance.now()将大致等于Date.now().



对于日志记录,您可以使用

如果要测量操作所花费的时间(以毫秒为单位)并将其记录到控制台,请使用以下命令:

console.time('Search page');
  doSomething();
console.timeEnd('Search page');
 

 function doSomething(){    
       for(i=0;i<1000000;i++){var x = i*i;}
 }

结果:

定时器名称:0.013ms

您可以更改不同操作的Timer-Name.

例:

    var t0 = performance.now();
    doSomething();
    var t1 = performance.now();

    console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.");
            
    function doSomething(){    
       for(i=0;i<1000000;i++){var x = i*i;}
    }

2 个回答
  • jsbin.com demo

    您将看到演示代码只是一个启动/停止/重置毫秒计数器.如果你想在时间上做出奇特的格式,那完全取决于你.这应该足以让你入门.

    这是一个有趣的小项目.这就是我接近它的方式

    var Stopwatch = function(elem, options) {
    
      var timer       = createTimer(),
          startButton = createButton("start", start),
          stopButton  = createButton("stop", stop),
          resetButton = createButton("reset", reset),
          offset,
          clock,
          interval;
    
      // default options
      options = options || {};
      options.delay = options.delay || 1;
    
      // append elements     
      elem.appendChild(timer);
      elem.appendChild(startButton);
      elem.appendChild(stopButton);
      elem.appendChild(resetButton);
    
      // initialize
      reset();
    
      // private functions
      function createTimer() {
        return document.createElement("span");
      }
    
      function createButton(action, handler) {
        var a = document.createElement("a");
        a.href = "#" + action;
        a.innerHTML = action;
        a.addEventListener("click", function(event) {
          handler();
          event.preventDefault();
        });
        return a;
      }
    
      function start() {
        if (!interval) {
          offset   = Date.now();
          interval = setInterval(update, options.delay);
        }
      }
    
      function stop() {
        if (interval) {
          clearInterval(interval);
          interval = null;
        }
      }
    
      function reset() {
        clock = 0;
        render();
      }
    
      function update() {
        clock += delta();
        render();
      }
    
      function render() {
        timer.innerHTML = clock/1000; 
      }
    
      function delta() {
        var now = Date.now(),
            d   = now - offset;
    
        offset = now;
        return d;
      }
    
      // public API
      this.start  = start;
      this.stop   = stop;
      this.reset  = reset;
    };
    

    获取一些基本的HTML包装器

    <!-- create 3 stopwatches -->
    <div class="stopwatch"></div>
    <div class="stopwatch"></div>
    <div class="stopwatch"></div>
    

    用法很简单

    var elems = document.getElementsByClassName("stopwatch");
    
    for (var i=0, len=elems.length; i<len; i++) {
      new Stopwatch(elems[i]);
    }
    

    作为奖励,您还可以获得定时器的可编程API.这是一个用法示例

    var elem = document.getElementById("my-stopwatch");
    var timer = new Stopwatch(elem, {delay: 10});
    
    // start the timer
    timer.start();
    
    // stop the timer
    timer.stop();
    
    // reset the timer
    timer.reset();
    

    jQuery插件

    至于jQuery部分,一旦你有如上所述的良好代码组合,编写一个jQuery插件就是一个简单的模式

    (function($) {
    
      var Stopwatch = function(elem, options) {
        // code from above...
      };
    
      $.fn.stopwatch = function(options) {
        return this.each(function(idx, elem) {
          new Stopwatch(elem, options);
        });
      };
    })(jQuery);
    

    jQuery插件用法

    // all elements with class .stopwatch; default delay (1 ms)
    $(".stopwatch").stopwatch();
    
    // a specific element with id #my-stopwatch; custom delay (10 ms)
    $("#my-stopwatch").stopwatch({delay: 10});
    

    2023-02-13 15:19 回答
  • 如果您需要微秒精度使用:

    performance.now ( - >浏览器支持)

        var t0 = performance.now();
        doSomething();
        var t1 = performance.now();
    
        console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.");
                
        function doSomething(){    
           for(i=0;i<1000000;i++){var x = i*i;}
        }
    2023-02-13 15:19 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有