timer

JS Countdown :

Using Localstorage.

H
H
:
M
M
:
S
S

Summary:


This is a javascript countdown timer using localstorage. We are simply storing the timer value in localstorage which will reinitialize the timer value when the user will refresh the page.

We need to store 'Stop Time' in milisecond in localstorage and hence the logic is :

Stop Time = Current Time + Countdown Time.

After refreshing the web page, we will get the 'stop time' from the localstorage. The diffrence between the 'current time' & the 'stop time' will give you the value of 'countdown time'. We will be using the 'countdown time' value in the javascript interval function.


1. Following is the code to store 'Stop Time' in the localstorage.

	function saveStopTime(stopTime){
		localStorage.setItem('stopTime',stopTime)
	}
		

2. Below is the code to start the Countdown Interval.

	function startTimer(totalTime){
		clearInterval(timer)
		timer = setInterval(function(){
			totalTime--
			$('#timer').html(secondsToHms(totalTime))
		}, 1000);
	}
		

3. Following is the code to get the countdown data from the user & start the functionality.

	function countdownStart() {
		var hour = parseInt($('#h1').val() + "" + $('#h2').val() || 0)
		var min = parseInt($('#m1').val() + "" + $('#m2').val() || 0)
		var sec = parseInt($('#s1').val() + "" + $('#s2').val() || 0)

		var totalTime = hour * 60 * 60 + min *60 + sec
		totalTime = totalTime * 1000
		var currentTime = new Date()
		saveStopTime(currentTime.getTime() + totalTime)
		startTimer(totalTime/1000)
	}
		

4. Following is the code to stop the interval & clear the timer data.

	function clearTimer(){
		$('#h1').val(0)
		$('#h2').val(0)
		$('#m1').val(0)
		$('#m2').val(0)
		$('#s1').val(0)
		$('#s2').val(0)
		$('#timer').html("")
		localStorage.removeItem('stopTime')
		clearInterval(timer)
	}
		

5. Create the function to convert the 'seconds' into - hour, minute & seconds.

	function secondsToHms(d) {
		d = Number(d);
		var h = Math.floor(d / 3600);
		var m = Math.floor(d % 3600 / 60);
		var s = Math.floor(d % 3600 % 60);

		var hDisplay = h > 0 ? h + (h == 1 ? " hour, " : " hours, ") : "";
		var mDisplay = m > 0 ? m + (m == 1 ? " minute, " : " minutes, ") : "";
		var sDisplay = s > 0 ? s + (s == 1 ? " second" : " seconds") : "";
		return hDisplay + mDisplay + sDisplay; 
	}
		

6. Creating the function to check whether the localstorage has 'Stop Time' value. If yes, it will initiate the timer.

	function checkHasTimer(){
		var stopTime = localStorage.getItem('stopTime')
		if(stopTime)
		{
			var currentTime = new Date()
			$('#timer').html(secondsToHms((stopTime - currentTime.getTime())/1000))
			startTimer((stopTime - currentTime.getTime())/1000)
		}
	}
		

Wishing You Luck!

Reach out for any further queries at : circlecodesolution@gmail.com

Thanks & Regards,

Nilesh Chavan.