如何使用JavaScript创建时间计数器?

时间:2016-05-10 06:28:03

标签: javascript jquery

我想创建一个时间计数器,它会显示他在加载后在该页面上花费的时间,点击某个按钮它将停止计数并显示他在该页面上花费的时间。我如何使用jQuery做到这一点?

我编写了一些javaScript代码,但无法正常工作。如果有人帮我找到解决方案。谢谢。

<html>
    <head>

        <title>Auto Refresh Page</title>
    <!--    <META HTTP-EQUIV="refresh" CONTENT="5">-->
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
     <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>
    </head>
    <body>
        <div>

        <div id="show" align="center"></div>
        <button id="myButton"></button>
        <script>


 $(document).ready(
                function () {
                function display() {
                   var startTime;
                    // later record end time
                    var endTime = new Date();

                    // time difference in ms
                    var timeDiff = endTime - startTime;

                    // strip the miliseconds
                    timeDiff /= 1000;

                    // get seconds
                    var seconds = Math.round(timeDiff % 60);

                    // remove seconds from the date
                    timeDiff = Math.floor(timeDiff / 60);

                    // get minutes
                    var minutes = Math.round(timeDiff % 60);

                    // remove minutes from the date
                    timeDiff = Math.floor(timeDiff / 60);

                    // get hours
                    var hours = Math.round(timeDiff % 24);

                    // remove hours from the date
                    timeDiff = Math.floor(timeDiff / 24);

                    // the rest of timeDiff is number of days
                    var days = timeDiff;

                    $(".show").text(days + " days, " + hours + ":" + minutes + ":" + seconds);
                    setTimeout(display, 1000);
                    }
                 $('#myButton').click(function(){
                 });
                });

        </script>
    </body>
</html>

2 个答案:

答案 0 :(得分:1)

您当前的代码存在三个主要问题。

首先,您永远不会初始化startTime变量,这意味着endTime - startTime会为您提供NaN。将以下行移出函数,以便它可以在调用之间保留其值:

var startTime;

...并给它一个起始值:

var startTime = new Date();

其次,您实际上从未实际调用过display();函数。您使用setTimeout()调用以便它自己调用,但您需要在声明后第一次调用它。所以在准备好的处理程序的末尾添加这一行:

display();

最后,您使用错误的选择器来显示时间。变化:

$(".show").text(...

是:

$("#show").text(...

如果您希望按钮停止时钟,则需要在函数外部添加一个变量,该变量将保存setTimeout()返回的ID,然后在按钮单击处理程序中调用clearTimeout()。 / p>

把所有这些放在一起:

&#13;
&#13;
$(document).ready(
  function() {
    var startTime = new Date();
    var timeoutId;
    function display() {
      var endTime = new Date(); // later record end time
      var timeDiff = endTime - startTime; // time difference in ms
      timeDiff /= 1000; // strip the miliseconds
      var seconds = Math.round(timeDiff % 60); // get seconds
      timeDiff = Math.floor(timeDiff / 60); // remove seconds from the date
      var minutes = Math.round(timeDiff % 60); // get minutes
      timeDiff = Math.floor(timeDiff / 60); // remove minutes from the date
      var hours = Math.round(timeDiff % 24); // get hours
      timeDiff = Math.floor(timeDiff / 24); // remove hours from the date
      var days = timeDiff; // the rest of timeDiff is number of days

      $("#show").text(days + " days, " + hours + ":" + minutes + ":" + seconds);
      timeoutId = setTimeout(display, 1000);
    }
    $('#myButton').click(function() { clearTimeout(timeoutId); });
    display();
  });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="show" align="center"></div>
<button id="myButton">Stop</button>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

我制作了bin并希望它能为您效果,我对您的代码进行了一些更改,您可以根据自己的需要进行修改。

// webpack.dev.config
var helpers = require('./helpers');
var webpackMerge = require('webpack-merge');
var commonConfig = require('./webpack.common.js');
var DefinePlugin = require('webpack/lib/DefinePlugin');


const ENV = process.env.ENV = process.env.NODE_ENV = 'development';
const METADATA = webpackMerge(commonConfig.metadata, {
    host: 'localhost',
    port: 8000,
    ENV: ENV
});


module.exports = webpackMerge(commonConfig, {

debug: true,
metadata: METADATA,
devtool: 'source-map',

output: {

    path: helpers.root('www'),
    filename: '[name].bundle.js',
    sourceMapFilename: '[name].map',
    chunkFilename: '[id].chunk.js'

},

plugins: [
    new DefinePlugin({
        'ENV': JSON.stringify(METADATA.ENV)
    }),
],
devServer: {
    port: METADATA.port,
    host: METADATA.host,
    historyApiFallback: true,
    watchOptions: {
        aggregateTimeout: 300,
        poll: 1000
    }
},
eslint: {
    configFile: './.eslintrc.js',
    emitError: false,
    emitWarning: false,
    fix: true
},

node: {
    global: 'window',
    crypto: 'empty',
    process: true,
    module: false,
    clearImmediate: false,
    setImmediate: false
}
});