JavaScript 实现用户行为日志收集(定时、定量以及关闭浏览器时向后台发送数据)

<button onclick="addLog()"> 记录日志</button>

<script>
var foo = function (){
    var queue = [];
    var timeInterval;
    var intervalInit = 10;
	var maxLogNum = 10;

    function clear () {
        queue.forEach(el => el())
        queue.length = 0
        window.clearInterval(timeInterval)
		//发送日志数据
        //var ajax = new XMLHttpRequest();
        //ajax.open("GET", 'http://localhost:8754/api/test/ok', true)
        //ajax.send(null);
    }
    window.onbeforeunload  = clear
    function keepTime () {
        if (intervel == 0) {
            clear()
        }
        console.log("interval",intervel)
        intervel --;
    }
    return {
        add: function (call) {
            window.clearInterval(timeInterval)
            timeInterval = setInterval(keepTime,1000)
            intervel = intervalInit
            queue.push(call)
            queue.length > maxLogNum && clear()
        },
        clear
    }
}

var target = foo()
var index = 0
function addLog(){
    target.add(_ => {
        console.log("TODO...",index ++)
    })
}
</script>
posted @ 2021-01-23 13:48  believexin  阅读(359)  评论(0编辑  收藏  举报