Javascript跟踪脚本轮询

时间:2014-08-22 20:23:03

标签: javascript

我有以下JS跟踪代码:

var jTGateway = "trackingurl";
var jTGatewaySSL = "trackingurl";
var jTDomain = "trackingurl";
var jTUser = "";
var jTPage = "";
var jTProtocol = window.location.protocol;
var jTImage = document.createElement('img');
var jTChatElement; var jTSession; var jTUrl;
jTImage.border = 0;
(function () {
if (jTUser == "") {
    var dt = new Date(); var jTCookie = document.cookie.toString();
    if (jTCookie.indexOf("jtrack") == -1) { jTSession = parseInt(Math.random() *     1000)     + "-" + dt.getTime(); document.cookie = "jtrack=" + jTSession + ";expires=Thu, 31-Dec-2020 00:00:00 GMT; path=/"; }
    jTCookie = document.cookie.toString();
    if (jTCookie.indexOf('jtrack') == -1) { jTSession = ""; } else {
        var s = jTCookie.indexOf("jtrack=") + "jtrack=".length; var e = jTCookie.indexOf(";", s);
        if (e == -1) e = jTCookie.length; jTSession = jTCookie.substring(s, e);
    } 
}
if (jTProtocol == "https:") jTGateway = jTGatewaySSL; if (jTUser != "") jTSession =     jTUser; if (jTProtocol == "file:") jTProtocol = "http:";
})();

function jTTrackPage() {
if (jTPage == "") jTPage = escape(window.location);
jTUrl = jTProtocol + "//" + jTGateway + "/jtrack.ashx?u=" + jTSession + "&d=" + jTDomain;
jTUrl += "&p='" + jTPage + "'&r='" + escape(document.referrer) + "'";
jTImage.src = jTUrl;
}

我在我的页面上将其称为:

    <script type='text/javascript' >
        if (typeof jTTrackPage == 'function') jTTrackPage();
    </script>

我的问题是,是否可以让它每隔10秒拨打一次电话呢?显示用户仍在页面上。我该怎么做呢?任何指针赞赏。谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用setInterval

window.setInterval(jTTrackPage, 10000); // call it every 10 000 ms = 10 s

setTimeout

function trackPage() {
    jTTrackPage();
    window.setTimeout(trackPage), 10000); // call the function again in 10 000 ms
}
trackPage();

两者之间的区别在于第一个调用它每隔10秒,如果一个调用超过10秒(此处不太可能),则下一个调用将在之后触发,而不等待10秒。第二种解决方案解决了这个问题。


您可以分别使用clearIntervalclearTimeout清除间隔或超时:

var interval = window.setInterval(jTTrackPage, 10000);

window.clearInterval(interval); // <-- stop it

var timeout = window.setTimeout(trackPage, 10000);

window.clearTimeout(timeout); // <-- stop it