如何使用JavaScript创建秒表?

max*_*sme 30 javascript jquery

if(stopwatch >= track[song].duration)
Run Code Online (Sandbox Code Playgroud)

track[song].duration 找到soundcloud轨道的持续时间.

我期待创建一个秒表功能,当你点击swapID 时开始计算毫秒数,stopwatch这样当函数被"点击"一段时间后,if函数会做一些事情.在我的情况下,替换图像.此外,当再次单击时,该功能将自行重置.

所以喜欢stopwatch= current time- clicked time如何设置clicked time

current time= new Date().getTime();?这是几毫秒?

$('#swap').click(function()...
Run Code Online (Sandbox Code Playgroud)

mač*_*ček 80

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;
};
Run Code Online (Sandbox Code Playgroud)

获取一些基本的HTML包装器

<!-- create 3 stopwatches -->
<div class="stopwatch"></div>
<div class="stopwatch"></div>
<div class="stopwatch"></div>
Run Code Online (Sandbox Code Playgroud)

用法很简单

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

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

作为奖励,您还可以获得定时器的可编程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();
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

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});
Run Code Online (Sandbox Code Playgroud)

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

Sub*_*dar 11

A simple and easy clock for you and don't forget me ;)

var x;
var startstop = 0;

function startStop() { /* Toggle StartStop */

  startstop = startstop + 1;

  if (startstop === 1) {
    start();
    document.getElementById("start").innerHTML = "Stop";
  } else if (startstop === 2) {
    document.getElementById("start").innerHTML = "Start";
    startstop = 0;
    stop();
  }

}


function start() {
  x = setInterval(timer, 10);
} /* Start */

function stop() {
  clearInterval(x);
} /* Stop */

var milisec = 0;
var sec = 0; /* holds incrementing value */
var min = 0;
var hour = 0;

/* Contains and outputs returned value of  function checkTime */

var miliSecOut = 0;
var secOut = 0;
var minOut = 0;
var hourOut = 0;

/* Output variable End */


function timer() {
  /* Main Timer */


  miliSecOut = checkTime(milisec);
  secOut = checkTime(sec);
  minOut = checkTime(min);
  hourOut = checkTime(hour);

  milisec = ++milisec;

  if (milisec === 100) {
    milisec = 0;
    sec = ++sec;
  }

  if (sec == 60) {
    min = ++min;
    sec = 0;
  }

  if (min == 60) {
    min = 0;
    hour = ++hour;

  }


  document.getElementById("milisec").innerHTML = miliSecOut;
  document.getElementById("sec").innerHTML = secOut;
  document.getElementById("min").innerHTML = minOut;
  document.getElementById("hour").innerHTML = hourOut;

}


/* Adds 0 when value is <10 */


function checkTime(i) {
  if (i < 10) {
    i = "0" + i;
  }
  return i;
}

function reset() {


  /*Reset*/

  milisec = 0;
  sec = 0;
  min = 0
  hour = 0;

  document.getElementById("milisec").innerHTML = "00";
  document.getElementById("sec").innerHTML = "00";
  document.getElementById("min").innerHTML = "00";
  document.getElementById("hour").innerHTML = "00";

}
Run Code Online (Sandbox Code Playgroud)
<h1>
  <span id="hour">00</span> :
  <span id="min">00</span> :
  <span id="sec">00</span> :
  <span id="milisec">00</span>
</h1>

<button onclick="startStop()" id="start">Start</button>
<button onclick="reset()">Reset</button>
Run Code Online (Sandbox Code Playgroud)


Leg*_*nds 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;}
    }
Run Code Online (Sandbox Code Playgroud)

与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;}
 }
Run Code Online (Sandbox Code Playgroud)

结果:

定时器名称: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;}
    }
Run Code Online (Sandbox Code Playgroud)