JavaScript (HTML5): タイマーを実行

snippet-timer.js

javascript: snippet-timer.js

(function() {
	function SnippetTimer() {
		this.label = document.createElement("div");
		document.body.appendChild(this.label);
		this.textNode = document.createTextNode("");
		this.label.appendChild(this.textNode);
		
		var startButton = document.createElement("input");
		startButton.type = "button";
		startButton.value = "start";
		document.body.appendChild(startButton);
		var that = this;
		startButton.onclick = function() {
			that.startTimer();
		};
		
		var stopButton = document.createElement("input");
		stopButton.type = "button";
		stopButton.value = "stop";
		document.body.appendChild(stopButton);
		stopButton.onclick = function() {
			that.stopTimer();
		};
	};
	SnippetTimer.prototype.startTimer = function() {
		this.stopTimer();
		var that = this;
		this.interval = setInterval(function() {
			that.tick();
		}, 1000);
	};
	SnippetTimer.prototype.stopTimer = function() {
		clearInterval(this.interval);
	};
	SnippetTimer.prototype.tick = function() {
		var date = new Date();
		var dateString = date.toLocaleString();
		this.textNode.data = dateString;
	};
	function loaded() {
		window.snippet = new SnippetTimer();
	}
	
	if(document.addEventListener){
		document.addEventListener("DOMContentLoaded", loaded, false);
	} else if(/msie/.test(navigator.userAgent.toLowerCase())){
		try {
			document.documentElement.doScroll("left");
		} catch(error){
			setTimeout(arguments.callee, 0);
			return;
		}
		loaded();
	}
}).call(this);