Trying to pause and resume a timer with same button - javascript

I am having a little trouble with this code. I am currently have a button that when clicked starts a timer. It then also changes the icon of the button from a start icon to a stop icon. I would like to stop this timer when the button is clicked again and have it switch back the icon from start to stop. I have been stuck for awhile and tried many things but cant get it to work and would appreciate any help. I am sure its a simple issue I am just new to javascript. Thanks.
(function () {
"use strict";
var minutesLabel = document.getElementById('t1-min'),
secondsLabel = document.getElementById('t1-sec'),
resetButton = document.getElementById('t1-reset'),
startButton = document.getElementById('t1-play'),
timer = null;
function getTimeRemaining(endtime) {
var t = Date.parse(endtime) - Date.parse(new Date());
var seconds = Math.floor((t / 1000) % 60);
var minutes = Math.floor((t / 1000 / 60) % 60);
return {
'total': t,
'minutes': minutes,
'seconds': seconds
};
}
function initializeClock(endtime) {
var timeinterval = setInterval(function () {
var t = getTimeRemaining(endtime);
if (t.total <= 0) {
clearInterval(timeinterval);
}
minutesLabel.innerHTML = t.minutes;
secondsLabel.innerHTML = pad(t.seconds);
}, 1000);
}
startButton.onclick = function runClock() {
var timeInMinutes = minutesLabel.innerHTML,
currentTime = Date.parse(new Date()),
deadline = new Date(currentTime + timeInMinutes * 60 * 1000);
initializeClock(deadline);
startButton.innerHTML = ('<i class="far fa-stop-circle fa-2x float-right">');
}
function pad(val) {
var valString = val + "";
if (valString.length < 2) {
return "0" + valString;
} else {
return valString;
}
}
})();

Firstly, make sure that the event listener in placed correctly on the startButton element by adding a function on addEventLister method like that:
startButton.addEventListener("click", function() {
//code goes here
});
Then initialize the timeinterval variable in the global scope of the code so that it can be accessed from all functions, and add a const in which you can save the initial text of the startButton:
(function () {
"use strict";
const START_BUTTON_INITIAL_TEXT = "Start"; // initial constant text of the start button
var minutesLabel = document.getElementById('t1-min'),
secondsLabel = document.getElementById('t1-sec'),
resetButton = document.getElementById('t1-reset'),
startButton = document.getElementById('t1-play'),
timer = null,
timeinterval; // declared in the global scope
Then add an id equal to t1-stop for the stopButton icon element to make sure that it can be accurately accessed by the Javascript file from the DOM:
startButton.innerHTML = ('<i id="t1-stop" class="far fa-stop-circle fa-2x float-right">');
lastly add this if statement in addEventListener function of startButton to check whether a stop button exists in the DOM when the startButton is clicked:
startButton.addEventListener("click", function() {
if (document.getElementById("t1-stop") != null) {
clearInterval(timeinterval);
var stopButton = document.getElementById("t1-stop");
startButton.removeChild(stopButton);
startButton.innerHTML = START_BUTTON_INITIAL_TEXT;
}
The above code stops the timeinterval and removes the stopButton from the DOM then replaces the innerHTML of startButton with the initial text set as a constant at the top variable declaration.
All in all, your event listener function for the startButton should look something like that:
startButton.addEventListener("click", function() {
if (document.getElementById("t1-stop") != null) {
clearInterval(timeinterval);
var stopButton = document.getElementById("t1-stop");
startButton.removeChild(stopButton);
startButton.innerHTML = START_BUTTON_INITIAL_TEXT;
return;
}
var timeInMinutes = minutesLabel.innerHTML,
currentTime = Date.parse(new Date()),
deadline = new Date(currentTime + timeInMinutes * 60 * 1000);
initializeClock(deadline);
startButton.innerHTML = ('<i id="t1-stop" class="far fa-stop-circle fa-2x float-right">');
});

Related

Javascript Stopwatch. Need help to store my timer and when page refresh to keep the time and continue from there

I have a working stopwatch. When I click start button the stopwatch is starting and when I click pause button the stopwatch is paused. What I would like is when I refresh my browser to keep the current time of the stopwatch and continue from there with the same functionality. Or when I echo the stopwatch time from a database to continue from the exact time it was before is saved it.
let showTime = document.querySelector("#output");
let startTimeButton = document.querySelector("#start")
let pauseTimeButton = document.querySelector("#pause")
pauseTimeButton.style.display = "none";
let seconds = 0;
let interval = null;
const timer = () => {
seconds++;
// Get hours
let hours = Math.floor(seconds / 3600);
// Get minutes
let minutes = Math.floor((seconds - hours * 3600) / 60);
// Get seconds
let secs = Math.floor(seconds % 60);
if (hours < 10) {
hours = `0${hours}`;
}
if (minutes < 10) {
minutes = `0${minutes}`;
}
if (secs < 10) {
secs = `0${secs}`;
}
showTime.innerHTML = `${hours}:${minutes}:${secs}`;
};
startTimeButton.addEventListener("click", () => {
pauseTimeButton.style.display = "block";
startTimeButton.style.display = "none";
console.log("START TIME CLICKED");
if (interval) {
return;
}
interval = setInterval(timer, 1000);
});
// Pause function
pauseTimeButton.addEventListener("click", () => {
pauseTimeButton.style.display = "none";
startTimeButton.style.display = "block";
console.log("PAUSE TIME CLICKED");
clearInterval(interval);
interval = null;
});
<button id="start">Start</button>
<button id="pause">Pause</button>
<div id="output"></div>
You could use localStorage.
In order to save each second passed you could modify your timer function to save to localStorage:
let seconds = 0;
if (localStorage.getItem("stopwatchSeconds") != null) {
seconds = parseInt(localStorage.getItem("stopwatchSeconds"));
}
//...
const timer = () => {
//...
seconds++;
localStorage.setItem("stopwatchSeconds", seconds);
//...
};
//...
I hope this helps.
It seems like what you're looking for is localStorage. You store your stopwatch data, such as startAt, totalSeconds in the storage and when you refresh the page you can restore your stopwatch state based on the saved data: remainingTime = (startAt + totalSeconds) - currentTime
localStorage docs: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Client-side_storage#storing_simple_data_%E2%80%94_web_storage

Pause/Continue in Pomodoro Timer project

I am building a pomodoro tracker in order to practice a little bit of JavaScript. It's been a while since I started this project. After this particulary problem which is implement a pause/continue functionality I abandoned the project. I really got stucked. I know programming is not easy and I will be facing many problems in the future but I really can't figure out how to solve this task. I am feeling stupid
Here is the JavaScript code:
// General Variables
let display = document.querySelector('.display');
// is the timer paused?
// let isPaused = true;
// let count = 0;
//const playPomodoro = document.querySelector('.play');
const pause = document.querySelector('.pause');
const resume = document.querySelector('.resume');
const stopPomodoro = document.querySelector('.stop');
const pomodoro = document.querySelector('#pomodoro');
const shortBreak = document.querySelector('#shortbreak');
const longBreak = document.querySelector('#longbreak')
const audioBeep = document.querySelector('#audioBeep');
const twentyFiveMinutes = 60 * 25;
const fiveMinutes = 60 * 5;
const thirtyMinutes = 60 * 30;
// Start Pomodoro timer 25 minutes
pomodoro.addEventListener('click', () => {
startTimer(twentyFiveMinutes, display);
stopClick(shortBreak, longBreak);
pause.style.display = 'block';
stopPomodoro.style.display = 'block';
});
// Start Pomodoro short break
shortBreak.addEventListener('click', () => {
startTimer(fiveMinutes, display);
stopClick(pomodoro, longBreak);
pause.style.display = 'block';
stopPomodoro.style.display = 'block';
});
// Start Pomodoro Long break
longBreak.addEventListener('click', () => {
startTimer(thirtyMinutes, display);
stopClick(pomodoro, shortBreak);
pause.style.display = 'block';
stopPomodoro.style.display = 'block';
});
// Stopping Clicks Events
function stopClick(btn1, btn2) {
btn1.classList.add('avoid-clicks');
btn2.classList.add('avoid-clicks');
}
// Remove .avoid-clicks class
function removeAvoidClick(btn1, btn2, btn3) {
btn1.classList.remove('avoid-clicks');
btn2.classList.remove('avoid-clicks');
btn3.classList.remove('avoid-clicks');
}
// main start timer function
function startTimer(duration, display) {
let timer = duration, min, sec;
let countingDown = setInterval(function() {
min = parseInt(timer / 60, 10);
sec = parseInt(timer % 60, 10);
min = min < 10 ? "0" + min : min;
sec = sec < 10 ? "0" + sec : sec;
display.innerHTML = min + ":" + sec;
if (--timer < 0) {
timer = duration;
}
// stops the counting variable when it hits zero
if (timer == 0) {
clearInterval(countingDown);
display.innerHTML = "00:00";
audioBeep.play();
removeAvoidClick(pomodoro,shortBreak,longBreak);
}
// Pause the clock
pause.addEventListener('click', () => {
});
// Stop the counter and set it to 00:00 when the user clicks the stop button
stopPomodoro.addEventListener('click', () => {
clearInterval(countingDown);
display.innerHTML = "00:00";
removeAvoidClick(pomodoro,shortBreak,longBreak);
});
}, 1000);
}
I will store the timer status in an object, then you activate a timer that decreses the current time left and call UI update.
let timer = {
timeLeft: 0,
running: 0,
};
function startTimer(duration) {
timer.timeLeft = duration;
if (!timer.run) {
timer.run = true;
run();
}
}
function run() {
if (timer.run) {
timer.timeLeft -= 1;
setTimeout(run, 1000)
}
}
function pauseTimer() {
timer.run = false;
}
function resumeTimer() {
if (!timer.run) {
timer.run = true;
run();
}
update();
}
function update() {
// everything you need to update in the UI from the timer object
}

Javascript Second into Minutes:Seconds

I am working on a clock that needs to display seconds into a
minutes:seconds
format.
I have worked on some auxiliary functions for display, but I have never really gotten the full display. Here is some of my code:
var time = 1500;
//Must declare timeHandler as global variable for stopTimer()
var timeHandler;
//Set intial HTML to time
document.getElementById("timer").innerHTML = display;
//Timer function for start button
function timer() {
timeHandler = setInterval(function() {
if (time > 0) {
time--;
document.getElementById("timer").innerHTML = time;
}
}, 1000);
}
//Stop function for stop button
function stopTimer() {
clearTimeout(timeHandler);
}
//Timer Display
var minutes = time/60;
var second = time%60;
var display = minutes + ":" + seconds;
HTML:
<h1> Pomodoro Clock</h1>
<!--Place holder for timer-->
<div id="timer" class="circle">Timer</div>
<!--//Start Button-->
<button onclick="setTimeout(timer, 1000);">Start</button>
<!--Stop Button-->
<button onclick="stopTimer()">Stop</button>
Thie formatTime function below will take a number of seconds, and convert it to MM:SS format (including padded zeroes):
var time = 1500;
//Must declare timeHandler as global variable for stopTimer()
var timeHandler;
//Set intial HTML to time
document.getElementById("timer").innerHTML = display;
//Timer function for start button
function timer() {
timeHandler = setInterval(function() {
if (time > 0) {
time--;
document.getElementById("timer").innerHTML = formatTime(time);
}
}, 1000);
}
//Stop function for stop button
function stopTimer() {
clearTimeout(timeHandler);
}
function formatTime(seconds) {
//Timer Display
var minutes = seconds / 60;
var second = seconds % 60;
return ('0'+minutes).substr(-2) +":"+ ('0'+seconds).substr(-2);
}
first of all you have to use clearInterval, then you don't update your display every second
check this fiddle out

Timer is not getting reset using clearInterval()

This is my Timer function
var myTimer = setInterval(function () {
var d = new Date();
var seconds = d.getMinutes() * 60 + d.getSeconds();
var fiveMin = 60 * 5;
var timeleft = fiveMin - seconds % fiveMin;
var result = parseInt(timeleft / 60) + ':' + timeleft % 60;
//console.log(result);
var timerObj = {
timer : result
}
$scope.timerArray = timerObj;
$scope.$apply();
if (timeleft === 1) {
$scope.statusDetails = [];
$scope.timeDetails();
$scope.get_dbStatus();
}
}, 1000);
This function will reset the above timer when I click a button.
$scope.refreshStatusList = function(){
$scope.hide = true;
$scope.$emit('LOAD');
clearInterval(myTimer);
$scope.statusDetails = [];
$scope.timeDetails();
$scope.get_dbStatus();
};
This is my refresh button in html page upon clicking it the timer must get reset.
<div class="col-lg-2">
<a href="#" title="Refresh" ng-click="refreshStatusList();">
<i class="fa fa-refresh fa-lg"></i>
</a>
</div>
Since, you are using angularjs, You should use $interval directive, which will internally call $scope.apply()
Usage
$scope.intervalPromise = $interval(function () {
//Your code
}, 1000);
To clear interval
$interval.cancel($scope.intervalPromise);
Try using this
$scope.apply();

Countdown timer javascript mins into hours

I'm a beginner in JavaScript, I wrote a countdown timer, but I don't know how to convert the mins into hours. I think its not to hard, but I can't do it, whenever I wrote new rows its not working. Here is my code:
var minutesRemaining;
var secondsRemaining;
var intervalHandle;
function resetPage() {
document.getElementById('inputArea').style.display = 'block';
//hide pause button by default
document.getElementById("pauseArea").style.display = "none";
//hide resume button
document.getElementById("resumeArea").style.display = "none";
}
function resumeCountdown() {
tick();
intervalHandle = setInterval(tick, 1000);
//hide resume button when resuming
document.getElementById("resumeArea").style.display = "none";
//show resume button;
document.getElementById("pauseArea").style.display = "block";
return;
}
function pauseCountdown() {
clearInterval(intervalHandle);
document.getElementById("pauseArea").style.display = "none";
document.getElementById("resumeArea").style.display = "block";
return;
}
function tick() {
//grab h1
var timeDisplay = document.getElementById('time');
//turn seconds into mm:55
var min = Math.floor(secondsRemaining / 60);
var sec = secondsRemaining - (min * 60);
//add leading 0 if seconds less than 10
if (sec < 10) {
sec = '0' + sec;
}
//concatenate with colon
var message = min.toString() + ':' + sec;
// now change the display
timeDisplay.innerHTML = message;
//stop if down to zero
if (secondsRemaining === 0) {
alert('Done!');
clearInterval(intervalHandle);
resetPage();
}
// subtract from seconds remaining
secondsRemaining--;
}
function startCountdown() {
//get contents
var minutes = document.getElementById('minutes').value;
//check if not a number
if (isNaN(minutes)) {
alert("Please enter a number!");
return;
}
//how many seconds?
secondsRemaining = minutes * 60;
//call tick
intervalHandle = setInterval(tick, 1000);
//hide form
document.getElementById('inputArea').style.display = 'none';
//show pause when running
document.getElementById("pauseArea").style.display = "block";
}
window.onload = function () {
// create text input
var inputMinutes = document.createElement('input');
inputMinutes.setAttribute('id', 'minutes');
inputMinutes.setAttribute('type', 'text');
inputMinutes.setAttribute('placeholder', 'Idő megadása');
//pause button
var pauseButton = document.getElementById("pauseBtn");
pauseButton.onclick = function() {
pauseCountdown();
};
//resume button
var resumeButton = document.getElementById("resumeBtn");
resumeButton.onclick = function() {
resumeCountdown();
};
//create button
var startButton = document.createElement('input');
startButton.setAttribute('type', 'button');
startButton.setAttribute('value', 'Indítás');
startButton.onclick = function () {
startCountdown();
};
// add to DOM
document.getElementById('inputArea').appendChild(inputMinutes);
document.getElementById('inputArea').appendChild(startButton);
document.getElementById("pauseArea").appendChild(pauseButton);
document.getElementById("resumeArea").appendChild(resumeButton);
//hide pause button by default
document.getElementById("pauseArea").style.display = "none";
//hide pause button by default
document.getElementById("resumeArea").style.display = "none";
};
Here is what i just wrote really quick. It may help you. But you can just do some basic math to get your conversions and handle the remainder. Like so:
function countDown(future_date_in_millis) {
var date = new Date();
var current_time = date.getTime();
//get the future date and time
var future_date = future_date_in_millis.getTime(); //1438077258047; //date.getTime();
// get the duration in milliseconds
// 1 day = 86400000 millis
var duration = future_date - current_time;
var dd = Math.floor(duration / 86400000);
var remainder = duration % 86400000;
var hh = Math.floor(remainder / 3600000);
remainder = remainder % 3600000;
var mm = Math.floor(remainder / 60000);
remainder = remainder % 60000;
var ss = Math.floor(remainder / 1000);
var days = document.getElementById("dd");
var hours = document.getElementById("hh");
var minutes = document.getElementById("mm");
var seconds = document.getElementById("ss");
days.innerHTML = dd.toString();
hours.innerHTML = hh.toString();
minutes.innerHTML = mm.toString();
seconds.innerHTML = ss.toString();
}
window.setInterval(function () {
/// call your function here
var d = new Date("July 15, 2015 4:52:00 PM");
countDown(d);
}, 1000);

Categories