如何使用JavaScript创建秒表?

时间:2022-03-12 22:28:09
if(stopwatch >= track[song].duration)

track[song].duration finds the duration of a soundcloud track.

跟踪(歌曲)。持续时间可以找到soundcloud跟踪的持续时间。

I am looking to create a stopwatch function that starts counting milliseconds when you click on the swap ID stopwatch so that when the function has been "clicked" for a certain amount of time the if function will do something. In my case replace an image. And also that the function will reset it itself when clicked again.

我希望创建一个秒表函数,当您单击交换ID秒表时,它将开始计算毫秒数,以便当函数被“单击”一段时间后,if函数将做一些事情。在我的例子中,替换一个图像。同时,当再次点击时,函数会重新设置它自己。

so like stopwatch = current time - clicked time How can I set up the clicked time

就像秒表=当前时间点击时间我如何设置点击时间

current time = new Date().getTime(); ? And is this in milliseconds?

当前时间=新日期().getTime();吗?这是毫秒吗?

$('#swap').click(function()...

2 个解决方案

#1


71  

jsbin.com demo

jsbin.com演示

You'll see the demo code is just a start/stop/reset millisecond counter. If you want to do fanciful formatting on the time, that's completely up to you. This should be more than enough to get you started.

您将看到演示代码只是一个开始/停止/复位毫秒计数器。如果你想在时间上做一些奇特的格式,那完全取决于你自己。这就足够让你开始了。

This was a fun little project to work on. Here's how I'd approach it

这是一个有趣的小项目。这是我的方法

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;
};

Get some basic HTML wrappers for it

为它获取一些基本的HTML包装

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

Usage is dead simple from there

从这里开始,用法就非常简单了

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

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

As a bonus, you get a programmable API for the timers as well. Here's a usage example

另外,您还可以获得一个可编程的计时器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 plugin

As for the jQuery portion, once you have nice code composition as above, writing a jQuery plugin is easy mode

至于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 plugin usage

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});

#2


5  

If you need microsecond precision use:

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

performance.now ( --> Browser support)

的性能。现在(——>浏览器支持)

    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;}
    }

Unlike other timing data available to JavaScript (for example Date.now), the timestamps returned by Performance.now() are not limited to one-millisecond resolution. Instead, they represent times as floating-point numbers with up to microsecond precision.

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

Also unlike Date.now(), the values returned by Performance.now() always increase at a constant rate, independent of the system clock (which might be adjusted manually or skewed by software like NTP). Otherwise, performance.timing.navigationStart + performance.now() will be approximately equal to Date.now().

与Date.now()不同的是,Performance.now()返回的值总是以恒定的速度增加,与系统时钟无关(系统时钟可以手动调整或被NTP之类的软件扭曲)。否则,performance.timing。navigationStart + performance.now()大约等于日期。



For logging you can use:

对于日志,您可以使用:

If you want to measure time spent in milliseconds spent by an operation and log it to the console, just use this:

如果您想测量操作花费的时间(以毫秒为单位)并将其记录到控制台,只需使用以下方法:

console.time('Timer name');
// your time consuming operation
console.timeEnd('Timer name');

Result:

结果:

Timer name: 0.013ms

计时器的名字:0.013 ms

You can change the Timer-Name for different operations.

您可以为不同的操作更改时间名。

Example:

例子:

console.time('Search page');

setTimeout(function(){
  console.timeEnd('Search page');
},1500);

#1


71  

jsbin.com demo

jsbin.com演示

You'll see the demo code is just a start/stop/reset millisecond counter. If you want to do fanciful formatting on the time, that's completely up to you. This should be more than enough to get you started.

您将看到演示代码只是一个开始/停止/复位毫秒计数器。如果你想在时间上做一些奇特的格式,那完全取决于你自己。这就足够让你开始了。

This was a fun little project to work on. Here's how I'd approach it

这是一个有趣的小项目。这是我的方法

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;
};

Get some basic HTML wrappers for it

为它获取一些基本的HTML包装

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

Usage is dead simple from there

从这里开始,用法就非常简单了

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

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

As a bonus, you get a programmable API for the timers as well. Here's a usage example

另外,您还可以获得一个可编程的计时器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 plugin

As for the jQuery portion, once you have nice code composition as above, writing a jQuery plugin is easy mode

至于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 plugin usage

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});

#2


5  

If you need microsecond precision use:

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

performance.now ( --> Browser support)

的性能。现在(——>浏览器支持)

    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;}
    }

Unlike other timing data available to JavaScript (for example Date.now), the timestamps returned by Performance.now() are not limited to one-millisecond resolution. Instead, they represent times as floating-point numbers with up to microsecond precision.

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

Also unlike Date.now(), the values returned by Performance.now() always increase at a constant rate, independent of the system clock (which might be adjusted manually or skewed by software like NTP). Otherwise, performance.timing.navigationStart + performance.now() will be approximately equal to Date.now().

与Date.now()不同的是,Performance.now()返回的值总是以恒定的速度增加,与系统时钟无关(系统时钟可以手动调整或被NTP之类的软件扭曲)。否则,performance.timing。navigationStart + performance.now()大约等于日期。



For logging you can use:

对于日志,您可以使用:

If you want to measure time spent in milliseconds spent by an operation and log it to the console, just use this:

如果您想测量操作花费的时间(以毫秒为单位)并将其记录到控制台,只需使用以下方法:

console.time('Timer name');
// your time consuming operation
console.timeEnd('Timer name');

Result:

结果:

Timer name: 0.013ms

计时器的名字:0.013 ms

You can change the Timer-Name for different operations.

您可以为不同的操作更改时间名。

Example:

例子:

console.time('Search page');

setTimeout(function(){
  console.timeEnd('Search page');
},1500);