この記事は 約 0分20秒 で読めます。
setTimeoutを使ったストップウォッチをクラスベースにまとめました。
先人様たちの知識ありがとうございます(*´∀`*)(stackoverflow感謝w)
★コア
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
//ストップウォッチ (function(window, doc, $){ //コンストラクタ var Clock = function (options){ var _this = this, i; _this._events = {}; _this.options = { delay : 1000 }; for(i in options) _this.options[i] = options[i]; }; Clock.prototype = { totalSeconds : 0, timerId : null, tick : null, remaining : null, start : function(){ var _this = this; _this.remaining = _this.options.delay; _this.resume(); }, pause : function(){ var _this = this; clearTimeout(_this.timerId); delete _this.timerId; _this.remaining -= new Date() - _this.tick; }, resume : function(){ var _this = this; _this.tick = new Date(); _this.timerId = setTimeout(function() { _this.remaining = _this.options.delay; _this.totalSeconds++; //console.log(parseInt(_this.totalSeconds)); _this.resume(); }, _this.remaining); }, getSeconds : function(){ var _this = this; return _this.totalSeconds; }, setSeconds : function(value){ var _this = this; _this.totalSeconds = value; } }; if (typeof exports !== 'undefined') exports.Clock = Clock; else window.Clock = Clock; })(this, document, jQuery); |
★使用例
1 2 3 4 5 6 7 8 9 10 |
var StopWatch = new Clock({}); StopWatch.start(); StopWatch.puase(); StopWatch.resume(); //ゲッター StopWatch.getSeconds(); //セッター StopWatch.setSeconds(***); |