代码之家  ›  专栏  ›  技术社区  ›  tkotitan

使用jQuery以毫秒为单位记录持续时间?

  •  2
  • tkotitan  · 技术社区  · 16 年前

    Javascript确实有一个精确到ms的计时器,对吧?那么jQuery是否使保持两次单击之间的时间这一任务变得简单了呢?

    1 回复  |  直到 16 年前
        1
  •  6
  •   T.J. Crowder    16 年前

    这不需要jQuery。要以毫秒为单位获取用户计算机上的时间:

    var nowInMilliseconds = new Date().getTime();
    

    所以要比较两次,只需从结束时间中减去开始时间,这就是毫秒的区别。

    例子:

    (function() {
        var firstClick;
    
        function clickHandler() {
            var now, duration;
    
            now = new Date().getTime();
            if (!firstClick) {
                // Remember the time of the first click
                firstclick = now;
            }
            else {
                // Second click; how long as it been?
                duration = now - firstClick;
    
                // Reset so we're waiting for the first click again
                firstClick = undefined;
    
                // ...send your Ajax data to the server...
            }
        }
    
        function pageLoad() {
            $('#button').click(clickHandler);
        }
    
        window.onload = pageLoad; // or jQuery.ready() or whatever
    })();