Adding a "Pause" Button to the Timer - Exercise

Contact Us or call 1-877-932-8228
Adding a "Pause" Button to the Timer - Exercise

Adding a "Pause" Button to the Timer

Duration: 10 to 20 minutes.

In this exercise, you will add a "Pause" button to the timer.

  1. Open DynamicForms/Exercises/Timer.html for editing.
  2. This page is the same as DynamicForms/Demos/Timer.html, except that it has a new "Pause" button that, when clicked, calls the pauseTimer() function. Your job is to create this pauseTimer() function and to modify the script so that the right buttons are enabled at the right times. The diagram below shows the three different phases:
  3. Test your solution in a browser.

Solution:

DynamicForms/Solutions/Timer.html
---- C O D E   O M I T T E D ----

<script type="text/javascript">
	function resetTimer(seconds){
		var btnStart = document.getElementById("btnStart");
		var btnPause = document.getElementById("btnPause");
		var btnReset = document.getElementById("btnReset");
		document.getElementById("timeLeft").value = seconds;
		clearInterval(timer);
		btnStart.disabled = false;
		btnPause.disabled = true;
		btnReset.disabled = true;
	}
	
	function decrementTimer(){
		var timeLeft = document.getElementById("timeLeft");
		var btnStart = document.getElementById("btnStart");
		var btnPause = document.getElementById("btnPause");
		var btnReset = document.getElementById("btnReset");
		timesUp = false;
		btnStart.disabled = true;
		btnPause.disabled = false;
		btnReset.disabled = false;
		timeLeft.value--;
		if (timeLeft.value < 0) {
			resetTimer(10);
			alert("Time's up!");
		}
	}
	
	function pauseTimer() {
		var btnStart = document.getElementById("btnStart");
		var btnPause = document.getElementById("btnPause");
		clearInterval(timer);
		btnPause.disabled = true;
		btnStart.disabled = false;
	}
	
	var timer, timesUp;
	observeEvent(window,"load",function() {
		var timeLeft = document.getElementById("timeLeft");
		var btnStart = document.getElementById("btnStart");
		var btnReset = document.getElementById("btnReset");
		observeEvent(btnStart,"click",function() {
			timer=setInterval(decrementTimer, 1000);
		});
		observeEvent(btnPause,"click",function() {
			pauseTimer();
		});
		observeEvent(btnReset,"click",function() {
			resetTimer(10);
		});
		observeEvent(timeLeft,"focus",function() {
			timeLeft.blur();
		});
	});
</script>
---- C O D E   O M I T T E D ----
Next