Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   Кнопка останов для функции с таймером (https://javascript.ru/forum/misc/60560-knopka-ostanov-dlya-funkcii-s-tajjmerom.html)

Lecseus 07.01.2016 10:22

Кнопка останов для функции с таймером
 
Здравствуйте. реализовал таймер, но никак не могу найти информации про остановку определенной функции кнопкой. В поиске по сайту есть похожее, но не совсем подходит.
<!DOCTYPE HTML>
 
<html>
 
<head>
  <title>Untitled</title>
  <meta charset="utf-8">
</head>
 
<body>
<script>
var mins = 90;  //Set the number of minutes you need
    var secs = mins * 60;
    var currentSeconds = 0;
    var currentMinutes = 0;
    /* 
     * The following line has been commented out due to a suggestion left in the comments. The line below it has not been tested. 
     * setTimeout('Decrement()',1000);
     */
    setTimeout(Decrement,1000); 

    function Decrement() {
        currentMinutes = Math.floor(secs / 60);
        currentSeconds = secs % 60;
        if(currentSeconds <= 9) currentSeconds = "0" + currentSeconds;
        secs--;
        document.getElementById("timer_").innerHTML = currentMinutes + ":" + currentSeconds; //Set the element id you need the time put into.
        if(secs !== -1) setTimeout('Decrement()',1000);	
		if(mins == 0 || secs == 0) window.location.replace("http://stackoverflow.com"); //if time ends its redirrecting to another page
    }
</script>
<button id="stop">Stop</button>
<div id="timer_" style="color: #000; font-size: 150%; font-weight: bold;">

подскажите, как привязать кнопку Stop к функции, чтобы эта самая кнопка останавливала действие функции с таймером?

Keramet 07.01.2016 11:29

<!DOCTYPE HTML>
<html>
<head>
	<title>Untitled</title>
	<meta charset="utf-8">
</head>
<body>
	<script>
		var mins = 90;  //Set the number of minutes you need
		var secs = mins * 60;
		var currentSeconds = 0;
		var currentMinutes = 0;
		var tmr; 
		
		
		tmr = setTimeout(Decrement,1000);

		function Decrement() {
			console.log(secs);
			currentMinutes = Math.floor(secs / 60);
			currentSeconds = secs % 60;
			if(currentSeconds <= 9) currentSeconds = "0" + currentSeconds;
			secs--;
			document.getElementById("timer_").innerHTML = currentMinutes + ":" + currentSeconds; //Set the element id you need the time put into.
			if(secs !== -1) { tmr = setTimeout('Decrement()',1000); } 
			if(mins == 0 || secs == 0) window.location.replace("http://stackoverflow.com"); //if time ends its redirrecting to another page
		}
		
		function stopTime(tmr) {
			clearTimeout(tmr);
		}
	</script>
	<button id="stop" onclick="stopTime(tmr)">Stop</button>
	<div id="timer_" style="color: #000; font-size: 150%; font-weight: bold;">
</body>
</html>

Lecseus 07.01.2016 17:22

идеально, так все просто оказывается. спасибо!!
не могли бы пояснить строчку console.log(secs); ? для чего она нужна?
и ещё такой вопрос, могу ли я на одну кнопку повесить выполнение двух функций, одна например останавливает таймер, а другая показывает скрытый блок?

Keramet 07.01.2016 19:01

1.
console.log(secs);
это я для себя, можете её убрать! (я ведь тоже учусь :yes: )

2. Да, можно.

Keramet 07.01.2016 19:14

<!DOCTYPE HTML>
<html>
<head>
	<title>Timer + hideDiv</title>
	<meta charset="utf-8">
</head>
<body>
	<script>
		"use strict";
		var mins = 90;  //Set the number of minutes you need
		var secs = mins * 60;
		var currentSeconds = 0;
		var currentMinutes = 0;
		var tmr; 
	
		tmr = setTimeout(Decrement,1000);

		function Decrement() {
			currentMinutes = Math.floor(secs / 60);
			currentSeconds = secs % 60;
			if(currentSeconds <= 9) currentSeconds = "0" + currentSeconds;
			secs--;
			document.getElementById("timer_").innerHTML = currentMinutes + ":" + currentSeconds;
			if(secs !== -1) { tmr = setTimeout('Decrement()',1000); } 
			if(mins == 0 || secs == 0) window.location.replace("http://stackoverflow.com"); 
		}
		
		window.onload = function() {
			var myBtn = document.getElementById('stop');
			
			myBtn.onclick = function() {
				var hideDiv = document.getElementById('note');
				
				if (myBtn.innerText == 'Stop') {
					clearTimeout(tmr);
					myBtn.innerText = 'Start';
					hideDiv.style.display = 'block';
				} else {
					Decrement();
					myBtn.innerText = 'Stop';
					hideDiv.style.display = 'none';
				}
			}
		}
</script>
	<button id="stop">Stop</button>
	<div id="timer_" style="color: #000; font-size: 150%; font-weight: bold;"></div>
	<div id="note" style="display: none;" >Это скрытая информация!</div>
</body>
</html>

Lecseus 08.01.2016 07:49

<!DOCTYPE HTML>
<html>
<head>
    <title>Timer + hideDiv</title>
    <meta charset="utf-8">
</head>
<body>
    <script>
        "use strict";
        var mins = 90;  //Set the number of minutes you need
        var secs = mins * 60;
        var currentSeconds = 0;
        var currentMinutes = 0;
        var timer;
     
        timer = setTimeout(Decrement,1000);
 
        function Decrement() {
            currentMinutes = Math.floor(secs / 60);
            currentSeconds = secs % 60;
            if(currentSeconds <= 9) currentSeconds = "0" + currentSeconds;
            secs--;
            document.getElementById("timer_").innerHTML = currentMinutes + ":" + currentSeconds;
            if(secs !== -1) { timer = setTimeout('Decrement()',1000); }
            if(mins == 0 || secs == 0) window.location.replace("http://stackoverflow.com");
        }
         
       function appear(){
            var hidden = document.getElementById('note');
            hidden.style.display = 'block';
       }
       function stopTime(timer) {
            clearTimeout(timer);
        }
</script>
    <button id="stop" onClick="stopTime(timer); appear();">Stop</button>
    <div id="timer_" style="color: #000; font-size: 150%; font-weight: bold;"></div>
    <div id="note" style="display: none;" >Это скрытая информация!</div>
</body>
</html>


можно ещё такой вариант, упрощенный, может пригодиться кому.
спасибо за идеи


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