跟踪任务所花费的总时间


Track total time taken for a task

我正在构建一个站点,其中任务分配给每个用户,他/她需要在固定的时间内完成任务。为此,需要跟踪每项任务所花费的时间。我还需要跟踪用户是否在网站上闲置。

现在我可以使用以下代码执行此操作:

.HTML

 <a class="btn btn-success btn-lg" id="startTracking" role="button">Start Tracking</a>
    <a class="btn btn-danger btn-lg" id="endTracking" role="button">Stop Tracking</a>
    <h2 id="testingSince"></h2>

JAVASCRIPT

<script type="text/JavaScript">
  var totalSeconds = 0;
  var idleSeconds = 0;
  $(document).ready(function () {
    $('body').on('click','#startTracking',function(){
      //Increment the idle time counter every minute.
      var idleInterval = setInterval(timerIncrement, 1000); // 1 second
    });
    //Zero the idle timer on mouse movement.
    $(this).mousemove(function (e) {
      idleSeconds = 0;
    });
    $(this).keypress(function (e) {
      idleSeconds = 0;
    });
  });
  function timerIncrement() {
    totalSeconds += 1;
    idleSeconds += 1 ;
    if (idleSeconds > 600) { // 20 minutes
      alert('You have been sitting Idle for 10 Minutes');
    }
    $('#testingSince').text(timeStringfromSeconds(totalSeconds));
  }
  function timeStringfromSeconds(totalSeconds){
      var hours = Math.floor(totalSeconds / 36e2),
      mins = Math.floor((totalSeconds % 36e2) / 60),
      secs = Math.floor((totalSeconds % 60));
      return ("0" + hours).slice(-2)+':'+("0" + mins).slice(-2)+':'+("0" + secs).slice(-2);
  }
 </script>

因此,此代码效果很好,用户可以看到自单击按钮以来所花费的时间。它还跟踪用户空闲时间,并在 10 分钟后发出警报。

但是,这里唯一的问题是当页面重新加载时,计数器从0开始。 即 2 行:

var totalSeconds = 0;
var idleSeconds = 0;

我只希望计时器计数器不要重新启动并从其以前的值继续。

一种方法是使用 Cookie。所以我必须每秒更新它们,但我不确定这是否是一个好主意。

如果有任何其他方法或我需要使用浏览器cookie,请告诉我?

许多用户不允许在他们的计算机上使用 cookie。您永远不应该只依赖 cookie。也许你应该制作一些脚本,你可以每隔一秒、两五秒调用一次 ajax 并将经过的时间存储在会话中。