Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   js Таймер (как оптимизировать?) (https://javascript.ru/forum/misc/63921-js-tajjmer-kak-optimizirovat.html)

diga 08.07.2016 10:30

js Таймер (как оптимизировать?)
 
Доброго дня суток форумчане!
Необходимо было написать 4 таймера, при клике на кнопку "старт" срабатывали бы одновременно, я сделал, но получился не красивый и не оптимизированный код, помогите оптимизировать функционал!
Премного благодарен!

$( document ).ready(function() {
	"use strict";
	var Common = {
		initial_timer: function(){
            var self = this;
			this.status = 'stopped';
			this.initialTimes = [2*60*61,10*601,5*60*60,50*60*60];
			this.times = [2*60*61,10*601,5*60*60,50*60*60];
		},
		
		start_timer: function(){
			if (this.status == 'running'){
				return false;
			}
			var self = this;
			console.log("call start timer");
			this.status = 'running';
			this.setIntervalTimer();
			for (var i = 0; i < 4; i++) {
			  this.addClass(i, "running");
			}
		},
		
		stop_timer: function(){
			if (this.status == 'stopped'){
				return false;
			} 
			var self = this;
			this.status = 'stopped';
			console.log("call stop timer");
			for (var i = 0; i < 4; i++) {
			  this.removeClass(i, "running");
			}
			clearTimeout(this.timer);
		},
		
		updateView : function() {
			for (var i = 0; i < 4; i++) {
			  this.updateClock(i, this.times[i]);
			}
		},
			
		updateClock : function(id, time) {
			var element = document.getElementById("clock"+id);
			var formattedTime = this.formatTime(time);
			element.innerHTML = formattedTime;
		},
		
		addClass : function(id, className) {
			var element = document.getElementById("clock"+id);
			element.className += " " + className;
		},
		
		removeClass : function(id, className) {
			var element = document.getElementById("clock"+id);
			var exp = new RegExp(className);
			element.className = element.className.replace( exp , '' );
		},
		
		formatTime : function(time) {
            var minutes = Math.floor(time / 60);
            var seconds = Math.floor(time % 60);
            var hours = Math.floor(minutes / 60);
            minutes = Math.floor(minutes % 60);

            var result = "";
            if (hours < 10) result +="0";
            result += hours + ":";
            if (minutes < 10) result += "0";
            result += minutes + ":";
            if (seconds < 10) result += "0";
            result += seconds;

            return result;
		},
		
		setIntervalTimer: function() {
			this.timer = window.setInterval(this.countDownTimer, 1000);
		},
		
		countDownTimer: function() {
			console.log(Common.times);
			for (var i = 0; i < 4; i++) {
			  Common.times[i]++;
			  Common.updateClock(i,	Common.times[i]);
			}	
		},
		
		clearIntervalTimer: function() {
			if (this.timer) {
				window.clearInterval(this.timer);
				this.timer = null;
			}
		}
	}
	
	Common.initial_timer();
	
	$( "#start" ).click(function() {
		Common.start_timer();
	});
	$( "#stop" ).click(function() {
		Common.stop_timer();
	});
});


<html>
<head>
<title>ChessClock</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" charset="utf-8" src="timer.js"></script>

<link rel="stylesheet" type="text/css" href="timer.css">
</head>
<body>
<div class="timer">

  <div id="clock0" class="clock">
  	00:00
  </div>

  <div id="clock1" class="clock">
  	00:00
  </div>
  <div id="clock2" class="clock">
  	00:00
  </div>
  <div id="clock3" class="clock">
  	00:00
  </div>

  <div class="button">
  <button id="start" >Start</div>
  <button id="stop">Stop</div>
  </div>
  </div>
</body>
</html>

рони 08.07.2016 10:39

diga,
html строки внизу???

diga 08.07.2016 10:42

Цитата:

Сообщение от рони
html строки внизу???

эм, в смысле?

рони 08.07.2016 11:03

Цитата:

Сообщение от diga
<button id="stop">Stop</div>

странные теги

diga 08.07.2016 11:09

Цитата:

Сообщение от рони
странные теги

мой косяк, но это не суть)

рони 08.07.2016 12:08

таймеры на requestAnimationFrame
 
diga,
вариант ...
<!DOCTYPE HTML>

<html>

<head>
  <title>Untitled</title>
  <meta charset="utf-8">
  <style type="text/css">
  .clock{
    color: rgb(102, 255, 255);
     background-color: rgb(0, 0, 255);
     padding: 2px 4px;
     border-radius: 4px;
     display: inline-block;
  }

  .clock span{
    margin: 2px;
    font-weight: bold;
  }
  .clock .sp,.clock .time,.clock .spl{
    color: rgb(255, 255, 255);
    font-size: 20px;
  }
  .clock .sec {
    color: rgb(255, 255, 0);
  }

  </style>
</head>

<body>
  <div class="timer">

  <div class="clock"></div>
  <div class="clock"></div>
  <div class="clock"></div>
  <div class="clock"></div>

  <div class="button">
  <button class="start" >Start</button>
  <button class="stop" >Stop</button>
  </div>
</div>
<script>
function fn(f, a) {
    var c = {
        stop: true,
        start: performance.now(),
        time: 0,
        go: function() {
            c.stop = false;
            c.timer()
        },
        cls: ["hour", "sp", "min", "spl", "sec"],
        formatTime: function(b) {
            b = Math.floor(b / 1E3);
            var a = Math.floor(b / 60),
                d = Math.floor(a / 60);
            b %= 60;
            a %= 60;
            return [c.two(d % 24), ":", c.two(a), ":", c.two(b)]
        },
        two: function(b) {
            return (9 < b ? "" : "0") + b
        },
        timer: function() {
            c.start = performance.now();
            requestAnimationFrame(function g(e) {
                if (c.stop) return;
                e -= c.start;
                c.time += e;
                c.start = performance.now();
                e = c.formatTime(c.time);
                c.cls.forEach(function(a,
                    b) {
                    a.innerHTML = e[b]
                });
                requestAnimationFrame(g)
            })
        },
        init: function() {
            a = a.split(":");
            c.time = 36E5 * a[0] + 6E4 * a[1] + 1E3 * a[2];
            c.cls = c.cls.map(function(a) {
                var d = document.createElement("span");
                d.classList.add(a);
                f.appendChild(d);
                return d
            });
            c.timer()
        }
    };
    c.init();
    return c
}
window.addEventListener("DOMContentLoaded", function() {
    var divs = document.querySelectorAll(".clock"),
        st = document.querySelector(".stop"),
        go = document.querySelector(".start"),
        arr = ["02:08:41", "01:40:00", "05:00:00", "00:00:00"];
    arr = arr.map(function(time, i) {
        return fn(divs[i], time)
    });
    st.addEventListener("click", function() {
        arr.forEach(function(time) {
            time.stop = true
        })
    });
    go.addEventListener("click", function() {
        arr.forEach(function(time) {
            time.go()
        })
    })
});

</script>

</body>
</html>

destus 08.07.2016 12:30

diga,
Оптимизируется через эту библиотеку http://momentjs.com/. Ну вообще кода будет раз в 20 меньше и работать будет в столько же раз быстрее.

diga 08.07.2016 12:46

Цитата:

Сообщение от рони
diga,
вариант

тяжеловато, опыта моего не хватает чтоб понять, тогда следующий вопрос, чем мой вариант хуже?

рони 08.07.2016 13:09

diga,
setInterval -- сам по себе плохой метод, запуски могут накопится, плюс параметр пауза никогда не будет 1000 и скоро таймер начнёт отставать


Часовой пояс GMT +3, время: 11:21.