首页 > 解决方案 > 如何跟踪倒数计时器并存储时间以备后用

问题描述

我试图弄清楚是否有比我的方法更好的方法来跟踪和存储计时器的结果,无论是每秒还是每 X 秒,这样当用户再次返回页面时,可以再次使用这些数据并拿起它离开的地方。

我的方法是运行一个使用 AJAX 运行查询的循环 setTimeout()。我将它设置为每 5 秒执行一次,它可以工作,但我担心未来的性能,数百名用户几乎同时每 5 秒生成一个查询,我也不喜欢看到控制台被所有这些归档POST 事件,因为我不知道用户将如何解释它。

无论如何,这就是我的代码的样子。

//This setTimeout() is not the loop. This only generates a 5 seconds delay between a previous action and the recurring update and it only performs the delay once. This is for a personal need.

setTimeout(function(){
    duration = getSeconds(); //this gets the current seconds listed on the timer
    console.log(duration);
    runUpdateProgress(c_id, id, 0, duration, 0, 1); //this passes the parameters to the function that does the update in the database
}, 5000);


//Here's the function that runs the setTimeout() loop and performs the update ever x seconds.

function runUpdateProgress(c_id, id, progress, duration, status, action){
    var func = setTimeout(function start() {
        //console.log({c_id, id, progress, duration, status, action});
        if(action == 1){
            duration = getStopWatchSeconds();
            updateSaveLessonProgress(c_id, id, progress, duration, status, action);
            setTimeout(start, 5000);
        }else{
            clearTimeout(func);
        }
    }, 5000);       
}

该代码有效,它更新数据库并保持存储的时间,并且我可以在需要时获取上次存储的时间(可能会损失 5-8 秒,但没关系)。

我只是想知道当有大量用户触发此查询时,是否有更好的方法来执行此操作而无需敲击数据库。我还不确定这是否真的会影响现场环境中的表现,但欢迎任何更好的想法。

标签: phpjqueryajax

解决方案


推荐阅读