how to create click event to display set interval time - javascript

I have a Javascript setInterval function set up to display like a timer. I'd like to display the time that is on the timer when a "next" button is clicked so the user can see how long they've spent on a certain page. I'm unsure how to connect the setInterval with a click event. This is what I have, but it's not working.
let timerId = setInterval(function () {
document.getElementById("seconds").innerHTML = pad(++sec % 60);
document.getElementById("minutes").innerHTML = pad(parseInt(sec / 60, 10));
}, 1000);
function myFunction() {
alert document.getElementById("timerId").innerHTML = "Time passed: " + timerId);
}

This should solve your problem.
var initialTime = new Date().getTime();
var timeSpent='0:00';
var timeElement = document.getElementById("time");
timeElement.innerHTML = timeSpent;
let timerId = setInterval(function () {
var currentTime = new Date().getTime();
timeSpent = millisToMinutesAndSeconds(currentTime - initialTime)
timeElement.innerHTML = timeSpent;
}, 1000);
function millisToMinutesAndSeconds(millis) {
var minutes = Math.floor(millis / 60000);
var seconds = ((millis % 60000) / 1000).toFixed(0);
return minutes + ":" + (seconds < 10 ? '0' : '') + seconds;
}
function alertFn(){alert(timeSpent)}
document.getElementById("rightButton").addEventListener('click',alertFn);
document.getElementById("wrongButton").addEventListener('click',alertFn);
<h1 id="time"></h1>
<button id="rightButton">Right</button>
<button id="wrongButton">Wrong</button>

First of all, it would be better if you put setInterval method inside the function. After that you could give your function to an event listener as an argument.
Your code should look something like this
let timerId;
function displayTime() {
timerId = setInterval(() => {
// your code
}, 1000);
}
document.querySelector('button').addEventListener('click', displayTime)

Related

Why two timers starts javascript issue, when timer start & I press some another timer at that time both timers are running

So here I create one contdown web application using HTML, CSS and JS and now I am stuck that how to reset the intervel time out function when click on some another button.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Countdown Timer</title>
<link href='https://fonts.googleapis.com/css?family=Inconsolata' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="timer">
<div class="timer__controls">
<button data-time="20" value="20" class="timer__button">20 Secs</button>
<button data-time="300" value="300" class="timer__button">Work 5</button>
<button data-time="900" value="900" class="timer__button">Quick 15</button>
<button data-time="1200" value="1200" class="timer__button">Snack 20</button>
<button data-time="3600" value="3600" class="timer__button">Lunch Break</button>
<form name="customForm" id="custom">
<input id="customMin" placeholder="Enter Minutes" >
</form>
</div>
<div class="display">
<h1 id="display__time-left">00:00</h1>
<p id="display__end-time">Be Back At 00.00</p>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
Here in the script.js file as I mantioned , javascript uses the setTimeout feature of javascript to build one countdown web application and now when in a output browser I press Lunch time button it will show the timer for the next 1Hour and than it is stop in 00:00...
as I want if one timer is running and I press some another button or some custom input for taking seconds than at that time both timers are running.
So please provide the solution that what I have to do.
scripts.js
let allButtons = document.querySelectorAll(".timer__button");
let valueOfTime;
for (var i = 0; i < allButtons.length; i++) {
allButtons[i].addEventListener("click", function () {
valueOfTime = this.value;
BackAt();
});
}
setInterval(function () {
var minutes = Math.floor(valueOfTime / 60);
var seconds = valueOfTime % 60;
if (valueOfTime > 0) {
document.getElementById("display__time-left").innerHTML = minutes + ":" + seconds;
}
else{
document.getElementById("display__time-left").innerHTML = "00:00";
}
valueOfTime--;
}, 1000);
document.getElementById("customMin")
.addEventListener("keypress", function (event) {
if (event.key === "Enter") {
event.preventDefault();
let inputMin = document.getElementById("customMin").value *60;
inputBackAt(inputMin);
setInterval(function () {
var minutes = Math.floor((inputMin / 60));
var seconds = inputMin % 60;
if (inputMin > 0) {
document.getElementById("display__time-left").innerHTML =
minutes + ":" + seconds;
}
inputMin--;
}, 1000);
}
});
function BackAt() {
var minutes = Math.floor(valueOfTime / 60);
let currentHours=new Date().getHours();
let currentMin= new Date().getMinutes();
let x = currentMin + minutes;
if (x > 59) {
let remainingMinutes = x-60;
document.getElementById('display__end-time').innerHTML= `Be Back At ${currentHours+1} : ${remainingMinutes}`;
}
else{
let remainingMin =currentMin+minutes;
document.getElementById('display__end-time').innerHTML= `Be Back At ${currentHours} : ${remainingMin}`;
}
}
function inputBackAt(inputMin){
var minutes = Math.floor((inputMin/ 60));
let currentHours=new Date().getHours();
let currentMin= new Date().getMinutes();
let y = currentMin + minutes;
if (y> 59) {
let remainingMinutes = y-60;
document.getElementById('display__end-time').innerHTML= `Be Back At ${currentHours+1} : ${remainingMinutes}`;
}
else{
let remainingMin =currentMin+minutes;
document.getElementById('display__end-time').innerHTML= `Be Back At ${currentHours} : ${remainingMin}`;
}
}
when I click on one button and the timer is running , after some time when I press another button to start the new timer at that time both previous and current timer are running.
This defines a Timer class that instantiates an independent timer, then create multiple copies of it. The time for each timer as well as how long a "tick" can both be supplied as arguments to the constructor. Each time the timer ticks it can call the optional updateCallback to notify you.
The example starts three timers, one for three "minutes" (a minute it actually set to 3 seconds) that ticks every second, one for six "minutes" that ticks every 500 milliseconds and one for 15 "minutes" that ticks every 200 milliseconds.
Timer (seconds, period, update, reset)
seconds: How many seconds the timer should last
period: How long a "tick" is
update: [Optional] A callback that is called after every tick
reset: [Optional] A callback back that will be called when the timer ends (or if Timer.reset() is called)
let oneSecond = 500; // this should be 1000, set to 500 for the example
let oneMinute = 3; // this should be 60, set to 3 for the example
let sessionTime = 3;
function Timer(seconds, period, updateCallback, resetCallback) {
this.s = seconds;
this.p = period || oneSecond;
this.update = updateCallback || Function.prototype; // Use NOOP function as default
this.callback = resetCallback || Function.prototype; // Use NOOP function as default
this.reset = function() {
this.intervalId = clearInterval(this.intervalId)
this.callback()
}
this.start = function() { this.update(this.s); this.intervalId = setInterval(this.timer.bind(this), [ this.p ]) }
this.timer = function() { if (--this.s <= 0) this.reset(); this.update(this.s) }
}
function setTimeLeft(sec, id) {
document.getElementById(id || 'time-left').textContent = `${(''+ ~~(sec / oneMinute)).padStart(2, '0')}:${(''+ sec % oneMinute).padStart(2, '0')}`;
}
document.addEventListener("DOMContentLoaded", function() {
new Timer(sessionTime * oneMinute, 1000, setTimeLeft, () => console.log('check 1000ms')).start()
new Timer(6 * oneMinute, 500, (s) => { setTimeLeft(s, 'time-left2')}, () => console.log('check 500ms')).start()
new Timer(15 * oneMinute, 200, (s) => { setTimeLeft(s, 'time-left3')}, () => console.log('check 200ms')).start()
})
<span id='time-left'></span><br />
<span id='time-left2'></span><br />
<span id='time-left3'></span>

How to end my countdown timer when a button is clicked?

I'm trying to create a function that will end a countdown timer, or automatically make the minutes and seconds part of the countdown timer === 0; however, it seems that using clearInterval(time) doesn't seem to work! Could anyone point out how I might be able to achieve what I'm trying to do!
Note that I've made startingMinutes = 1 just for my ease.
Below is the countdown function and HTML:
// FUNCTION - countDown function that counts down from 8 minutes
const startingMinutes = 1;
let time = startingMinutes * 60;
function updateCountDown() {
const minutes = Math.floor(time / 60);
let seconds = time % 60;
seconds = seconds < 1 ? '0' + seconds : seconds;
document.getElementById("countdown").innerHTML = `${minutes}:${seconds}`;
time--;
time = time < 0 ? 0 : time;
if (minutes == 0 && seconds == 0) {
document.getElementById('tableStyle').style.display = "block";
document.getElementById('wordsIncluded').style.display = "block";
document.getElementById('show_header_one').style.display = "block";
recognition.abort(); //speech recognition stops when countdown timer ends
isListening = false;
}
//my attempt at clearing the countdowntimer!
window.addEventListener('DOMContentLoaded', function() {
document.getElementById("submit_button").addEventListener("click", function() {
clearInterval(time);
})});
HTML:
//where the countdown timer is displayed
<div id="circle"><p id="countdown">8:00</p></div>
//Click the below button and the countdown timer will end (minutes === 0 and seconds === 0)
<button id="submit_button" type="submit">Click to Submit</button>
To use clearInterval you need to pass it the value returned by setInterval
I have an example below using your code, where I pass the value from "setInterval" which I call "interval" to a function "stop" which calls "clearInterval" to stop the timer, and runs the code you were running.
let isListening = true;
const recognition = { abort: () => console.log('aborted') };
function updateCountDown(time) {
const minutes = Math.floor(time / 60);
const seconds = time % 60;
const timer = document.getElementById("countdown");
timer.textContent = `${minutes}:${seconds.toString().padStart(2, '0')}`;
}
function start(time) {
const interval = setInterval(() => {
if (--time) updateCountDown(time);
else stop(interval);
}, 1000);
document.getElementById("submit_button")
.addEventListener("click", () => stop(interval))
}
function stop(interval) {
updateCountDown(0); // This line sets time to 0
clearInterval(interval);
foo()
}
// I assume you want this to happen when the timer runs down or the button is clicked
function foo() {
document.getElementById('tableStyle').style.display = "block";
document.getElementById('wordsIncluded').style.display = "block";
document.getElementById('show_header_one').style.display = "block";
recognition.abort(); //speech recognition stops when countdown timer ends
isListening = false;
}
start(8*60)
#tableStyle, #wordsIncluded, #show_header_one { display: none; }
<p id="tableStyle">Table Style</p>
<p id="wordsIncluded">Words Included</p>
<p id="show_header_one">Show Header One</p>
<div id="circle">
<p id="countdown">8:00</p>
</div>
<button id="submit_button" type="submit">Click to Submit</button>
const startingMinutes = 1;
let time = startingMinutes * 60;
var abort_count_down = true;
function updateCountDown() {
if (abort_count_down) {
const minutes = Math.floor(time / 60);
let seconds = time % 60;
seconds = seconds < 1 ? '0' + seconds : seconds;
document.getElementById("countdown").innerHTML = `${minutes}:${seconds}`;
time--;
time = time < 0 ? 0 : time;
if (minutes == 0 && seconds == 0) {
document.getElementById('tableStyle').style.display = "block";
document.getElementById('wordsIncluded').style.display = "block";
document.getElementById('show_header_one').style.display = "block";
recognition.abort(); //speech recognition stops when countdown timer ends
isListening = false;
}
};
//my attempt at clearing the countdowntimer!
window.addEventListener('DOMContentLoaded', function() {
document.getElementById("submit_button").addEventListener("click", function() {
abort_count_down = false;
})});

How to make multiple countdown timers at the same page using the codes below?

How to make multiple countdown timers at the same page using the codes below?
I tried to make another countdown timer by making another var start = document.getElementById("start2"); and var dis = document.getElementById("display2"); but when I click the 1 button only the second countdown timer is working,
var start1 = document.getElementById("start1");
var dis1 = document.getElementById("display1");
var finishTime1;
var timerLength1 = 10;
var timeoutID1;
dis1.innerHTML = "" + timerLength1;
if(localStorage.getItem('myTime')){
Update();
}
start1.onclick = function () {
localStorage.setItem('myTime', ((new Date()).getTime() + timerLength1 * 1000));
if (timeoutID1 != undefined) window.clearTimeout(timeoutID1);
Update();
}
function Update() {
finishTime1 = localStorage.getItem('myTime');
var timeLeft = (finishTime1 - new Date());
dis1.innerHTML = "" + Math.max(timeLeft/1000,0)
timeoutID1 = window.setTimeout(Update, 100);
}
var start2 = document.getElementById("start2");
var dis2 = document.getElementById("display2");
var finishTime2;
var timerLength = 100;
var timeoutID;
dis2.innerHTML = "" + timerLength;
if(localStorage.getItem('myTime')){
Update();
}
start2.onclick = function () {
localStorage.setItem('myTime', ((new Date()).getTime() + timerLength * 1000));
if (timeoutID != undefined) window.clearTimeout(timeoutID);
Update();
}
function Update() {
finishTime2 = localStorage.getItem('myTime');
var timeLeft = (finishTime2 - new Date());
dis2.innerHTML = "" + Math.max(timeLeft/1000,0)
timeoutID = window.setTimeout(Update, 100);
}
<span id="display2"></span><button id="start1">START1</button>
<br><br>
<span id="display2"></span><button id="start1">START1</button>
enter code here
You are using the same id for localStorage. Actually it is better to create isolated context through function or class, then it will be easier to handle as much counters as you wish. Also you can use setInterval instead of setTimer
One more tip: when you assign number to string field no need to write "" + value, because number authomatically will be converted into string
const createCounter = (startElementId, displayElementId, localStorageId, timerLength) => {
const startElement = document.getElementById(startElementId),
displayElement = document.getElementById(displayElementId)
let timeoutID
displayElement.innerHTML = timerLength
const storageValue = localStorage.getItem(localStorageId)
if (storageValue) startTimer()
startElement.onclick = () => {
const value = (new Date()).getTime() + timerLength * 1000
localStorage.setItem(localStorageId, value)
startTimer()
}
function startTimer () {
if (timeoutID) clearInterval(timeoutID)
timeoutId = setInterval(updateTime, 100)
}
function updateTime (finishTime) {
finishTime = finishTime || localStorage.getItem(localStorageId)
const timeLeft = finishTime - new Date()
displayElement.innerHTML = Math.max(timeLeft / 1000, 0)
}
}
// run first timer for elements with ids start1 and display1
createCounter('start1', 'display1', 'someId1', 10)
// run second timer for elements with ids start1 and display1
createCounter('start2', 'display2', 'someId2', 60)
html
<button id=start1>Start</button>
<div id=display1></div>
<button id=start2>Start</button>
<div id=display2></div>

How to make a pause/play button for timer on Javascript?

I am trying to make my pause and play button function on javascript, but I don't exactly know the logic behind all of it
I have tried putting the clearInterval() method in my pauseTimer function
var startButton = document.getElementById("start");
var startSound = document.getElementById("audio");
var timerSound = document.getElementById("timer");
var counter = document.getElementById("counter");
var middlebuttons = document.getElementsByClassName("middlebuttons");
var pauseButton = document.getElementById("pause");
var playButton = document.getElementById('play');
function pauseTimer(){
clearInterval();
alert("Pause button");
}
function playTimer(){
alert("Play button");
}
function countDown(minutes){
var seconds = 60;
var mins = minutes;
function tick(){
var current_minutes = mins - 1;
seconds --;
counter.innerHTML = current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
if(seconds > 0){
setTimeout(tick, 10);
} else {
if(mins > 1){
countDown(mins - 1);
}
else if (mins && seconds === 0 ){
timerSound.play();
buttons();
}
}
}
tick();
}
pauseButton.addEventListener('click', pauseTimer, playAudio );
playButton.addEventListener('click', playTimer, playAudio );
Here's a thoroughly commented suggested solution. It uses a totalSeconds variable as the counter's source of truth.
The reason the timer variable is needed is because clearInterval wants to be told which interval to clear.
There's no "stop" button in this demo. If you want to reset the timer while it's running, just refresh the page.
(And it doesn't include any functions to play sounds, but you could add those at the appropriate points in the code.)
// Defines identifiers for accessing HTML elements
const minutesInput = document.getElementById("minutesInput"),
startButton = document.getElementById("startButton"),
pauseButton = document.getElementById("pauseButton"),
unpauseButton = document.getElementById("unpauseButton"),
counterDiv = document.getElementById("counterDisplay");
// Adds listeners and declares global variables
startButton.addEventListener('click', start);
pauseButton.addEventListener('click', pauseTimer);
unpauseButton.addEventListener('click', runTimer);
let totalSeconds; // global variable to count down total seconds
let timer; // global variable for setInterval and clearInterval
//Disables buttons that are not needed yet
disable(pauseButton);
disable(unpauseButton);
// Defines functions that get the minutes and seconds for display
function getMinutes(totalSeconds){
return Math.floor(totalSeconds / 60); // Gets quotient rounded down
}
function getSeconds(totalSeconds){
let seconds = totalSeconds % 60; // Gets remainder after division
return (seconds < 10 ? "0" + seconds : seconds) // Inserts "0" if needed
}
// Defines functions that manipulate the countdown
function start(){
totalSeconds = minutesInput.value * 60; // Sets initial value of totalSeconds based on user input
counterDiv.innerHTML = getMinutes(totalSeconds) + ":" + getSeconds(totalSeconds); // Initializes display
disable(minutesInput); disable(startButton); // Toggles buttons
runTimer();
}
function runTimer(){
// Is the main timer function, calls `tick` every 1000 milliseconds
timer = setInterval(tick, 1000);
disable(unpauseButton); enable(pauseButton); // Toggles buttons
}
function tick(){
if(totalSeconds > 0){
totalSeconds--; // Decreases total seconds by one
counterDiv.innerHTML = getMinutes(totalSeconds) + ":" + getSeconds(totalSeconds); // Updates display
}
else{
// The timer has reached zero. Let the user start again.
enable(minutesInput); enable(startButton);
disable(pauseButton); disable(unpauseButton);
}
}
function pauseTimer(){
// Stops calling `tick` and toggles buttons
clearInterval(timer);
disable(pauseButton); enable(unpauseButton);
}
// Defines functions to disable and re-enable HTML elements
function disable(element){ element.setAttribute("disabled",""); }
function enable(element){ element.removeAttribute("disabled"); }
counter{ height: 1em; width: 2em; margin: 0.4em; border: 1px solid grey }
<label>
How many minutes?:
<input type="number" id="minutesInput" value="1" />
</label>
<br />
<button id="startButton">Start</button>
<button id="pauseButton">Pause</button>
<button id="unpauseButton">Continue</button>
<div id="counterDisplay"></div>

Timer keeps getting faster on every reset

The timer keeps getting faster every time I reset it. I'm thinking I need to use clearTimeout but am unsure about how to implement it. Here's the code:
$(function(){
sessionmin = 25;
$("#sessionMinutes").html(sessionmin);
$("#circle").click(function() {
timeInSeconds = sessionmin * 60;
timeout();
});
})
function timeout(){
setTimeout(function () {
if (timeInSeconds > 0) {
timeInSeconds -= 1;
hours = Math.floor(timeInSeconds/3600);
minutes = Math.floor((timeInSeconds - hours*3600)/60);
seconds = Math.floor(timeInSeconds - hours*3600 - minutes*60);
$("#timer").html(hours + ":" + minutes + ":" + seconds);
}
timeout();
}, 1000);
}
You have to define your setTimeout as a variable to reset it.
See Fiddle
var thisTimer; // Variable declaration.
$(function(){
sessionmin = 25;
$("#sessionMinutes").html(sessionmin);
$("#circle").click(function(){
clearTimeout(thisTimer); // Clear previous timeout
timeInSeconds = sessionmin * 60;
timeout();
});
})
function timeout(){
thisTimer = setTimeout(function () { // define a timeout into a variable
if(timeInSeconds>0){
timeInSeconds-=1;
hours = Math.floor(timeInSeconds/3600);
minutes = Math.floor((timeInSeconds - hours)/60);
seconds = (timeInSeconds - hours*3600 - minutes*60)
$("#timer").html(hours + ":" + minutes + ":" + seconds);
}
timeout();
}, 1000);
}
You should: use setInterval instead of setTimeout, return the interval id that setInterval generates, clear that interval before you restart it. Here is an example: https://jsfiddle.net/8n2b7x0s/
$(function(){
var sessionmin = 25;
var intervalId = null;
$("#sessionMinutes").html(sessionmin);
$("#circle").click(function() {
timeInSeconds = sessionmin * 60;
// clear the current interval so your code isn't running multiple times
clearInterval(intervalId);
// restart the timer
intervalId = run();
});
})
function run(){
return setInterval(function () {
if(timeInSeconds>0){
timeInSeconds-=1;
hours = Math.floor(timeInSeconds/3600);
minutes = Math.floor((timeInSeconds - hours)/60);
seconds = (timeInSeconds - hours*3600 - minutes*60)
$("#timer").html(hours + ":" + minutes + ":" + seconds);
}
}, 1000);
}

Categories

Resources