Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   Переменная перетирается (https://javascript.ru/forum/misc/72176-peremennaya-peretiraetsya.html)

yaparoff 13.01.2018 14:44

Переменная перетирается
 
[Сообщение удалено]

рони 13.01.2018 15:47

yaparoff,
window.timerId = window.setInterval(tick(time), 1000);

window.timerId = window.setInterval(function() {
 time = tick(time)
}, 1000);



function tick(timerTime) {
    timerTime = timerTime - 1;
        //???
    showTime(timerTime);
    return timerTime;
}

Nexus 13.01.2018 16:38

Не знаю зачем я это сделал.
<!DOCTYPE html>
<html>
	<head>
		<title>Untitled</title>
		<style type="text/css">
			body {
				margin: 0;
				padding: 0;
				font-family: sans-serif;
			}
			ul {
				margin: 0;
				padding: 0;
				list-style-type: none;
			}
			.header {
				position: relative;
				background-color: slategray;
				padding: 20px 0;
				color: white;
			}

			.header__title {
				margin: 0;
				text-align: center;
			}

			.sign-link {
				position: absolute;
				right: 20px;
				top: 30px;
				cursor: pointer;
			}

			.timer {
				padding: 30px 0;
			}

			.timer__display {
				text-align: center;
				font-size: 50px;
				font-weight: bold;
				color: #5f6f80;
				text-shadow: 2px 2px 2px rgba(0,0,0, 0.3);
			}

			.timer__buttons {
				margin-top: 35px;
				text-align: center;
			}

			.timer__btn {
				display: inline-block;
				padding: 10px 20px;
				margin-right: 10px;
				border: 1px solid #000;
				font-weight: bold;
				border-radius: 5px;
				cursor: pointer;
				outline: none;
			}

			.timer__btn--start {
				background-color: green;
				color: #fff;
			}

			.timer__btn--stop {
				background-color: #c60f13;
				color: #fff;
			}

			.timer__options {
				text-align: center;
				margin-bottom: 30px;
			}
			.timer__option {
				display: inline-block;
				background-color: #2ba6cb;
				border: 1px solid #1e728c;
				transition: .4s;
				color: #fff;
				font-weight: bold;
				padding: 7px 30px;
				cursor: pointer;
			}
			.timer__option:hover,
			.timer__option:active,
			.timer__option--active {
				background-color: #2284a1;
			}
		</style>
		<script type="text/javascript">
			function CountDown(start_from,container){
			  start_from=!start_from?10:start_from;
			  container=(typeof container=='string')?document.querySelector(container):container;
			  if(!container)
				throw new Error('Container not found');
			  
			  this.__cfg={
				container:container,
				start_from:start_from,
				pause:true,
				counter:start_from,
				_timeout:0
			  };
			  this.__init();
			  this.__display(start_from);
			};
			CountDown.prototype.__cfg={};
			CountDown.prototype.start=function(){
			  this.__cfg.pause=false;
			};
			CountDown.prototype.stop=function(){
			  this.__cfg.pause=true;
			};
			CountDown.prototype.reset=function(){
			  this.__display(this.__cfg.counter=this.__cfg.start_from);
			};
			CountDown.prototype.__init=function(){
			  this.__cfg._timeout=setTimeout(function(){
				this.__init();
				if(!this.__cfg.pause && this.__cfg.counter>0)
				  this.__display(--this.__cfg.counter);
			  }.bind(this),1000);
			};
			CountDown.prototype.__display=function(seconds){
			  if((seconds=seconds||this.__cfg.counter)<0)
				  return;
			  
			  var mins=Math.floor(seconds/60)
			  this.__cfg.container.innerHTML=(mins<10?'0'+mins:mins)+':'
				+((seconds=(seconds=seconds-mins*60)<10?'0'+seconds:seconds));
			};
			CountDown.prototype.destruct=function(){
			  clearTimeout(this.__cfg._timeout);
			};
		</script>
	</head>
	<body>
		<div class="timer">
			<div class="timer__options">
				<div class="timer__option" data-seconds="1500">Pomodoro</div>
				<div class="timer__option" data-seconds="300">Short Time</div>
				<div class="timer__option" data-seconds="600">Long Time</div>
			</div>
			<div class="timer__display"></div>
			<div class="timer__buttons">
				<button class="timer__btn  timer__btn--start">Start</button>
				<button class="timer__btn  timer__btn--stop">Stop</button>
				<button class="timer__btn  timer__btn--reset">Reset</button>
			</div>
		</div>
		<script type="text/javascript">
			(function(){
			  var _get=function(sel,all){
					return document['querySelector'+(all?'All':'')](sel);
				  },
				  links=_get('[data-seconds]',true),
				  counter=undefined,
				  controls={
					start:'.timer__btn--start',
					stop:'.timer__btn--stop',
					reset:'.timer__btn--reset'
				  };
			  
			  Object.keys(controls).forEach(function(key){
				_get(controls[key]).addEventListener('click',function(){
				  if(!counter)
					return;
				  
				  counter[key]();
				});
			  });
			  
			  [].forEach.call(links,function(node){
				node.addEventListener('click',function(){
				  counter=(!counter || counter.destruct(),new CountDown(node.dataset.seconds,'.timer__display'));
				});
			  });
			  links[0].click();
			})(); 
		</script>
	</body>
</html>
https://codepen.io/anon/pen/eyKLEQ

yaparoff 13.01.2018 18:33

Цитата:

Сообщение от рони
window.timerId = window.setInterval(function() {
 time = tick(time)
}, 1000);

Да, оно! Ваш совет как обычно действенный. Спасибо!
Честно говоря, никогда не понимал разницу между
setInterval(tick(time), 1000)

и
setInterval(function() {
 time = tick(time)
}, 1000);

В чем разница?

Цитата:

Сообщение от рони
function tick(timerTime) {
    timerTime = timerTime - 1;
        //???
    showTime(timerTime);
    return timerTime;
}

А что тут? Что-то не так?

yaparoff 13.01.2018 18:40

Столкнулся с таким явлением
https://codepen.io/anon/pen/jYKQPb
Постарался указать все на скриншоте: http://skrinshoter.ru/s/130118/DW94uqOI?a
Как исправить это?
Т.е. когда таймер запущен и мы нажимаем кнопку "Стоп", а затем опять на "Старт", нужно чтобы отсчет продолжался и дальше, с того значения на котором остановились а не с самого начала

рони 13.01.2018 18:49

yaparoff,
форум - поиск - таймер

рони 13.01.2018 18:59

yaparoff,

как форум писал таймеры ...
Цитата:

Сообщение от Aetae
Вариант с прямым и обратным отсчётом, с установкой секунд, минут, часов, дней, недель, месяцев и лет, с сапёром и змейкой, с aero, с функцией gps, со звуками, распознаванием голоса и искусственным интеллектом ... ... и, наконец, с блэкджеком и шлюхами.

https://javascript.ru/forum/misc/239...tajjmer-3.html


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