Bye Bye Moore

PoCソルジャーな零細事業主が作業メモを残すブログ

setTimeoutで定期的にリロードする

Javascriptで、ページの特定の部分を書き換えるスクリプトです。
ただ読み込むだけでは芸が無いので、文字の色を一秒ごとに変える仕様にしてみました。
(仕事で書いた奴を少し改変しています。)

なお、10進数=>16進数のスクリプトはKawanet Blog II様からお借りしました。

<!-- ~/sample.html -->
<html>
  <head>
    <title>定期更新サンプル</title>
    <script type="text/javascript" src="js/main.js"></script>
  </head>
  <body>

    <form>
      <input type="button" value="タイマー始動" onClick="setTimer()">
      <input type="button" value="手動更新" onClick="swapColor(false)">
      <input type="button" value="タイマー解除" onClick="clearTimer()">
      <input type="button" value="再読み込み" onClick="location.reload()">
    </form>
    
    <div>
      <font id="result" size="2" color="#000000">
	一秒毎に色が変わるよ!
      </font>
    </div>
  </body>
</html>
// ~/js/main.js

function setTimer()
{
    timerID = setTimeout("swapColor(true)",100);
}


//設定されてるタイマーをクリアする
function clearTimer()
{
    clearTimeout(timerID);
 }

//色を変える。
//一応、引数でループするか聞く。
function swapColor(is_loop)
{
    var node     = document.getElementById("result");
    var rnd_color = ""
    var R = Math.floor(Math.random() * 255);
    var G = Math.floor(Math.random() * 255);
    var B = Math.floor(Math.random() * 255);

    rnd_color += "#" + dec2hex(R) + dec2hex(G) + dec2hex(B);
    node.color = rnd_color; 

    if (is_loop) {
        timerID = setTimeout("swapColor(true)",1000);
    }
}

//From http://kawa.at.webry.info/200511/article_7.html
function dec2hex (dec) {
    var hex = "";
    while( dec ) {
        var last = dec & 15;
        hex = String.fromCharCode(((last>9)?55:48)+last) + hex;
        dec >>= 4;
    }
    return hex;
}