LoginSignup
4
4

More than 5 years have passed since last update.

時間経過により何かするためのJavaScriptコード

Last updated at Posted at 2017-08-01

任意のページ滞在時間でイベントを起こすためのJavaScriptコード

指定のページ滞在時間が経過する度にintent()が実行され、カスタムイベントelpsTimeが発火する。
このコードは複数の滞在時間を設定しても同時に走るタイマー数を1つに抑えることにより、ページ負荷を軽減している。

;(function($) {
    var timerSec = [1, 3, 5, 8, 10, 30, 60, 61, 75];   // ここで目的の滞在時間を秒単位で設定

    var timerId = 0;
    var stayOverSec = 0;
    var now, start = new Date();

    var intent = function(sec){
        $(window).trigger('elpsTime', sec);
    };

    var timer = function(){
        clearInterval(timerId);
        stayOverSec = timerSec.shift();
        intent(stayOverSec);
        if(timerSec.length){
            now = new Date();
            timerId = setInterval(timer, timerSec[0]*1000 - (now - start));
        }
    };


    timerSec.sort(function(a,b){return a - b;});
    timerId = setInterval(timer, timerSec[0] * 1000);
})(jQuery);

以下のようなコードでカスタムイベントelpsTimeを捕捉できる。

$(window).on('elpsTime',function(){
    var toHms = function(rawSec){
        var hms= '';
        var h = rawSec / 3600 | 0;
        var m = rawSec % 3600 / 60 | 0;
        var s = rawSec % 60;
        if(h){ hms = h + 'h';}
        if(m){ hms += m + 'm';}
        if(s){ hms += s + 's';}
        return hms;
    };
    console.log(arguments[0].type + ': ' + toHms(arguments[1]));
});

実行結果

image.png

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4