一个简单的计时器

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_37064409/article/details/78866021
  • 从后台接收数据到前台展示,需要数据和时间轴一一对应,所以接收的数据都带有时间戳,只是每500ms数据传输一次,前台也需要500ms更新一次。前台展示的事件格式为: minute:second.millisecond (00:00.00) 都保留两位。

  • 效果如下:

这里写图片描述

  • 具体业务需求:当点击测试时开始计时,毫秒单位要么是.50,要么是00。接收的时间戳为1,2,3,4…分别对应500ms,1000ms,1500ms,2000ms 。秒和分钟60进位,正常逻辑。

  • 代码如下:

    function getMstime(date) {
        var s = 0,
            min = 0,
            _timer = "";
        seconds = Math.floor(date / 2 % 60);
        minutes = Math.floor(date / 120 % 60);
        if (date % 2 == 0) {
            _timer = getDouble(minutes) + ":" + getDouble(seconds) + ".00";
        } else {
            _timer = getDouble(minutes) + ":" + getDouble(seconds) + ".50";
        }
        console.log("min:%s,s:%s", minutes, seconds);
        return _timer;
    }
    // 补齐两位数
    function getDouble(num) {
        if (num < 10) {
            return '0' + num;
        } else {
            return '' + num;
        }
    }
  • 计时器调用
     //计时器
     setTimeout(() => {
         timer = setInterval(function(){
             time = getMstime(err_Time);
             $(".timeData").text(time);
         }, 500);
     }, 1000);

    1.err_Time:接收到的时间戳//1,2,3,4...
    2.因为websocket服务器有1.5s延迟,所以要先延迟1s后更新

猜你喜欢

转载自blog.csdn.net/weixin_37064409/article/details/78866021
今日推荐