コメント欄で思いがけず見つけたので、メモ。
prototype定義したメソッド内でsetTimeoutで自身を呼び出す方法
・JavaScript’s setTimeout and how to use it with your methods » Klevo blog
http://klevo.sk/javascript/javascripts-settimeout-and-how-to-use-it-with-your-methods/If you are using the prototype javascript, you can take advantage of its general purpose early-binding function, bind (see http://alternateidea.com/blog/articles/2007/7/18/javascript-scope-and-binding).
The solution using prototype’s bind function is:setTimeout(this.methodToCall.bind(this), time);
上記赤文字の通りに使えば良いのですが、メソッド自身を繰り返し呼んでブラウザに時計のように表示するサンプルを以下に。
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=utf-8" />
<title>BrowserTimer</title>
<meta name="author" content="takaiwa29" />
<script type="text/javascript">
var BrowserTimer = function() {}
BrowserTimer.prototype = {
timerMethod: function () {
// 現在時刻を取得
var nowtime = new Date();
var display = document.getElementById("display");
// 現在時刻を表示
display.innerHTML = nowtime.toString();
// 1秒後に同メソッドを呼ぶ
setTimeout(this.timerMethod.bind(this),1000);
}
}
function init() {
var hoge = new BrowserTimer();
hoge.timerMethod();
}
</script>
</head>
<body onLoad="init()">
<!-- タイマー表示場所 -->
<div id="display"></div>
</body>
</html>
実行結果はこんな感じ
コメント
コメントを投稿