[jsbin.com demo](http://jsbin.com/IgaXEVI/167/edit)
您会看到演示代码只是一个开始/停止/重置毫秒计数器。如果您想按时进行奇特的格式化,那完全取决于您。这应该足以让您入门。
这是一个有趣的小项目。这是我的处理方式
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 ></div><div ></div><div ></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 timertimer.start();// stop the timertimer.stop();// reset the timertimer.reset();jQuery插件
至于jQuery部分,一旦您拥有了上述不错的代码组成,编写jQuery插件就很容易了
(function($) { var Stopwatch = function(elem, options) { // pre 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});


