I am trying to have my alert show up with the time that my timer shows.
function Stopwatch(elem) {
var time = 0;
var offset;
var interval;
function update() {
if (this.isOn) {
time += delta();
}
elem.textContent = timeFormatter(time);
}
function delta() {
var now = Date.now();
var timePassed = now - offset;
offset = now;
return timePassed;
}
function timeFormatter(time) {
time = new Date(time);
var minutes = time.getMinutes().toString();
var seconds = time.getSeconds().toString();
var milliseconds = time.getMilliseconds().toString();
if (minutes.length < 2) {
minutes = '0' + minutes;
}
if (seconds.length < 2) {
seconds = '0' + seconds;
}
while (milliseconds.length < 3) {
milliseconds = '0' + milliseconds;
}
return minutes + ' : ' + seconds + ' . ' + milliseconds;
}
this.start = function() {
interval = setInterval(update.bind(this), 10);
offset = Date.now();
this.isOn = true;
};
this.stop = function() {
clearInterval(interval);
interval = null;
this.isOn = false;
};
this.reset = function() {
time = 0;
update();
};
this.isOn = false;
}
var timer = document.getElementById('timer');
var toggleBtn = document.getElementById('toggle');
var resetBtn = document.getElementById('reset');
var watch = new Stopwatch(timer);
function start() {
toggleBtn.textContent = 'Stop';
watch.start();
}
function stop() {
toggleBtn.textContent = 'Start';
watch.stop();
}
toggleBtn.addEventListener('click', function() {
watch.isOn ? stop() : start();
});
resetBtn.addEventListener('click', function() {
watch.reset();
});
function alertSystem(){
var timer = document.getElementById('timer')
alert(timer);
}
<h1 id="timer">00 : 00 . 000</h1>
<div>
<button class=button id="toggle">Start</button>
<button class=button id="reset">Reset</button>
<button onclick='alertSystem()'>get number</button>
</div>
It's a lot of code, but it is mostly to get the timer working. The last function called alertSystem() is on the bottom and is the one that triggers the alert call. For me the alert shows up as [object HTMLHeadingElement] or as undefined. The former comes up when I have alert(timer); but if I do alert(timer.value); or alert(timer.length); I get the latter.
Does anyone know how I can just get the value of the timer in the alert?
To get the timer's value, you should do something like:
document.querySelector('#timer').innerHTML
Otherwise , document.getElementById returns a full element as a js object.
Related
When I click the date value I'm having this error: Uncaught TypeError: Cannot read property 'textContent' of undefined
This is my code can you help me in determining the source of the error and how can I correct this?
function Timer(elem) {
var time = 3000;
var interval;
var offset;
function update() {`enter code here`
time += delta();
var formattedTime = timeFormatter(time);
elem.textContent = formattedTime;
}
function delta() {
var now = Date.now();
var timePassed = now - offset;
offset = now;
return timePassed;
}
function timeFormatter(timeInMilliseconds) {
var time = new Date(timeInMilliseconds)
var minutes = time.getMinutes().toString();
var seconds = time.getSeconds().toString();
if (minutes.length < 2) {
minutes = '0' + minutes;
}
if (seconds.length < 2) {
seconds = '0' + seconds;
}
return minutes + ' : ' + seconds;
}
this.isOn = false;
this.start = function() {};
if (!this.isOn) {
interval = setInterval(update, 10);
offset = Date.now();
this.isOn = true;
}
};
this.stop = function() {
if (this.isOn) {
clearInterval(interval);
interval = nul;
this.isOn = false;
}
};
this.reset = function() {};
Edited version for the other errors.
function Timer(elem) {
var time= 0;
var offset;
var interval;
function update() {
if (this.isOn) {
time += delta();
var formattedTime = timeFormatter(time);
}
elem.textContent = formattedTime;
}
function delta() {
var now = Date.now();
var timePassed = now - offset;
offset = "5:00";
return timePassed;
}
function timeFormatter(time) {
time = new Date(time);
var minutes = time.getMinutes().toString();
var seconds = time.getSeconds().toString();
if (minutes.length < 2) {
minutes = '0' + minutes;
}
if (seconds.length < 2) {
seconds = '0' + seconds;
}
return minutes + ' : ' + seconds;
}
this.start = function() {
interval = setInterval(update.bind(this), 10);
time++;
this.isOn = true;
};
this.stop = function() {
clearInterval(interval)
interval = null;
this.isOn = false;
};
this.reset = function() {
time= 300;
update();
};
this.isOn = false;
}
When I reload the page, my 1 minute countdown also reloads.
I tried to use localStorage but it seems to me failed.
Please have a look, I do not know where I should fix.
Thank you
My script
/* for countdown */
var countDown = (function ($) {
// Length ms
var timeOut = 10000;
// Interval ms
var timeGap = 1000;
var currentTime = (new Date()).getTime();
var endTime = (new Date()).getTime() + timeOut;
var guiTimer = $("#clock");
var running = true;
var timeOutAlert = $("#timeout-alert");
timeOutAlert.hide();
var updateTimer = function() {
// Run till timeout
if(currentTime + timeGap < endTime) {
setTimeout( updateTimer, timeGap );
}
// Countdown if running
if(running) {
currentTime += timeGap;
if(currentTime >= endTime) { // if its over
guiTimer.css("color","red");
}
}
// Update Gui
var time = new Date();
time.setTime(endTime - currentTime);
var minutes = time.getMinutes();
var seconds = time.getSeconds();
guiTimer.html((minutes < 10 ? '0' : '') + minutes + ':' + (seconds < 10 ? '0' : '') + seconds);
if (parseInt(guiTimer.html().substr(3)) <= 10){ // alert the user that he is running out of time
guiTimer.css('color','red');
timeOutAlert.show();
}
};
var pause = function() {
running = false;
};
var resume = function() {
running = true;
};
var start = function(timeout) {
timeOut = timeout;
currentTime = (new Date()).getTime();
endTime = (new Date()).getTime() + timeOut;
updateTimer();
};
return {
pause: pause,
resume: resume,
start: start
};
})(jQuery);
jQuery('#break').on('click',countDown.pause);
jQuery('#continue').on('click',countDown.resume);
var seconds = 60; // seconds we want to count down
countDown.start(seconds*1000);
I tried to fix it but I dont know where/how to put localStorage.
This may help you.
HTML Code:
<div id="divCounter"></div>
JS Code
var test = 60;
if (localStorage.getItem("counter")) {
if (localStorage.getItem("counter") <= 0) {
var value = test;
alert(value);
} else {
var value = localStorage.getItem("counter");
}
} else {
var value = test;
}
document.getElementById('divCounter').innerHTML = value;
var counter = function() {
if (value <= 0) {
localStorage.setItem("counter", test);
value = test;
} else {
value = parseInt(value) - 1;
localStorage.setItem("counter", value);
}
document.getElementById('divCounter').innerHTML = value;
};
var interval = setInterval(function() { counter(); }, 1000);
I am currently working on Pomodoro Clock project, everything seems working on plus/minus buttons in both Session and Break but time itself is not working (in blue circle area), something is little missing, please see below.
var time = document.querySelector(".time");
var timerBody = document.querySelector(".timerBody");
var currentWork = document.querySelector(".currentWork");
var sessionLength = document.querySelector(".sessionLength");
var minusSessionLength = document.querySelector(".minus-sessionLength");
var plusSessionLength = document.querySelector(".plus-sessionLength");
var breakLength = document.querySelector(".breakLength");
var minusBreakLength = document.querySelector(".minus-breakLength");
var plusBreakLength = document.querySelector(".plus-breakLength");
var isLoop = false;
var isSession = true;
var Sound = new Audio('http://www.oringz.com/oringz-uploads/sounds-917-communication-channel.mp3');
function GetTime(timeString){
timeString = timeString.split(':');
var seconds = parseInt(timeString[0]) * 60 + parseInt(timeString[1]);
return seconds;
}
// Errors here
function setTime(seconds) {
var timeString = [];
timeString.push(Math.floor(seconds/60));
timeString.push((seconds % 60 < 10) ? '0' + (seconds % 60).toString() : (seconds % 60));
return timeString.join(':')
}
var currentTime = GetTime(time.innerHTML);
minusSessionLength.addEventListener('click', function(event){
if(!isLoop) {
var STime = parseInt(sessionLength.innerHTML);
if(STime - 1 >= 1)
STime--;
sessionLength.innerHTML = STime;
if(isSession) {
time.innerHTML = STime + ':00';
currentTime = GetTime(time.innerHTML);
}
}
});
plusSessionLength.addEventListener('click', function(event){
if(!isLoop) {
var STime = parseInt(sessionLength.innerHTML);
sessionLength.innerHTML = ++STime;
if(isSession){
time.innerHTML = STime + ':00';
currentTime = GetTime(time.innerHTML);
}
}
});
minusBreakLength.addEventListener('click', function(event){
if(!isLoop) {
var BTime = parseInt(breakLength.innerHTML);
if(BTime - 1 >= 1) {
BTime--;
breakLength.innerHTML = BTime;
}
if(!isSession) {
time.innerHTML = BTime + ':00';
currentTime = GetTime(time.innerHTML);
}
}
});
plusBreakLength.addEventListener('click', function(event){
if(!isLoop) {
var BTime = parseInt(breakLength.innerHTML);
breakLength.innerHTML = ++BTime;
if(!isSession) {
time.innerHTML = BTime + ':00';
currentTime = GetTime(time.innerHTML);
}
}
});
var loop;
timerBody.addEventListener('click', function(event){
if(isLoop) {
clearInterval(loop);
currentWork.innerHTML = 'Paused';
isLoop = !isLoop;
}
else {
currentWork.innerHTML = isSession ? 'Session' : 'Break';
loop = setInterval(function() {
time.innerHTML = SetTime(--currentTime);
if(currentTime < 1) {
if(isSession) {
currentWork.innerHTML = 'Break';
time.innerHTML = breakLength.innerHTML + ':00';
currentTime = GetTime(time.innerHTML);
timerBody.style.borderColor = "#80FF80";
Sound.play();
var isBreakTitle = true;
var changeTitle = setInterval(function(){
document.title = isBreakTitle ? '***Break!***' : '************';
isBreakTitle = !isBreakTitle;
}, 100);
setTimeout(function() {
clearInterval(changeTitle);
document.title = 'Pomodoro clock';
}, 5000);
isSession = !isSession;
}
else {
currentWork.innerHTML = 'Session';
time.innerHTML = sessionLength.innerHTML + ':00';
currentTime = GetTime(time.innerHTML);
timerBody.style.borderColor = "#F64141";
Sound.play();
var isSessionTitle = false;
var changeTitle = setInterval(function() {
document.title = isSessionTitle ? '***Session!****' : '************';
isSessionTitle = !isSessionTitle;
}, 100);
setTimeout(function() {
clearInterval(changeTitle);
document.title = 'Pomodoro clock';
}, 5000);
isSession = !isSession;
}
}
}, 1000);
isLoop = !isLoop;
}
});
Here's mispelling mistake which should be "SetTime"
function SetTime(seconds) {
var timeString = [];
timeString.push(Math.floor(seconds/60));
timeString.push((seconds % 60 < 10) ? '0' + (seconds % 60).toString() : (seconds % 60));
return timeString.join(':')
}
Hope that helps to your future issues.
I'm trying to write with javascript and html how to display the time a user is idle (not moving mouse or pressing keys). While the program can detect mousemovements and key presses, the program for some reason isn't calling the idleTime() method which displays the time in minutes and seconds.
I'm wondering why the method isn't getting called, as if it is called it would display true or false if a button is pressed.
var startIdle = new Date().getTime();
var mouseMoved = false;
var buttonPressed = false;
function idleTime() {
document.write(buttonPressed);
if (mouseMoved || buttonPressed) {
startIdle = new Date().getTime();
}
document.getElementById('idle').innerHTML = calculateMin(startIdle) + " minutes: " + calculateSec(startIdle) + " seconds";
var t = setTimeout(function() {
idleTime()
}, 500);
}
function calculateSec(startIdle1) {
var currentIdle = new Date().getTime();
var timeDiff = Math.abs(currentIdle - startIdle1);
var idleSec = Math.ceil(timeDiff / (1000));
return idleSec % 60;
}
function calculateMin(startIdle1) {
var currentIdle = new Date().getTime();
var timeDiff = Math.abs(currentIdle - startIdle1);
var idleMin = Math.ceil(timeDiff / (1000 * 60));
return idleMin;
}
var timer;
// mousemove code
var stoppedElement = document.getElementById("stopped");
function mouseStopped() { // the actual function that is called
mouseMoved = false;
stoppedElement.innerHTML = "Mouse stopped";
}
window.addEventListener("mousemove", function() {
mouseMoved = true;
stoppedElement.innerHTML = "Mouse moving";
clearTimeout(timer);
timer = setTimeout(mouseStopped, 300);
});
//keypress code
var keysElement = document.getElementById('keyPressed');
window.addEventListener("keyup", function() {
buttonPressed = false;
keysElement.innerHTML = "Keys not Pressed";
clearTimeout(timer);
timer = setTimeout("keysPressed", 300);
});
window.addEventListener("keydown", function() {
buttonPressed = true;
keysElement.innerHTML = "Keys Pressed";
clearTimeout(timer);
timer = setTimeout("keyPressed", 300);
});
function checkTime(i) {
if (i < 10) {
i = "0" + i
}; // add zero in front of numbers < 10
return i;
}
Here is the HTML code:
<body onload="idleTime()">
<div id="stopped"><br>Mouse stopped</br></div>
<div id="keyPressed"> Keys not Pressed</div>
<strong>
<div id="header"><br>Time Idle:</br>
</div>
<div id="idle"></div>
</strong>
</body>
Actually the keysElement and stoppedElement were not referred firing before the DOM load. and also removed the document.write
Thats all all good. :)
var startIdle = new Date().getTime();
var mouseMoved = false;
var buttonPressed = false;
function idleTime() {
//document.write(buttonPressed);
if (mouseMoved || buttonPressed) {
startIdle = new Date().getTime();
}
document.getElementById('idle').innerHTML = calculateMin(startIdle) + " minutes: " + calculateSec(startIdle) + " seconds";
var t = setTimeout(function() {
idleTime()
}, 500);
}
function calculateSec(startIdle1) {
var currentIdle = new Date().getTime();
var timeDiff = Math.abs(currentIdle - startIdle1);
var idleSec = Math.ceil(timeDiff / (1000));
return idleSec % 60;
}
function calculateMin(startIdle1) {
var currentIdle = new Date().getTime();
var timeDiff = Math.abs(currentIdle - startIdle1);
var idleMin = Math.ceil(timeDiff / (1000 * 60));
return idleMin;
}
var timer;
// mousemove code
//var stoppedElement = document.getElementById("stopped");
function mouseStopped() { // the actual function that is called
mouseMoved = false;
document.getElementById("stopped").innerHTML = "Mouse stopped";
}
function keyStopped() { // the actual function that is called
buttonPressed = false;
document.getElementById("keyPressed").innerHTML = "Keys stopped";
}
window.addEventListener("mousemove", function() {
mouseMoved = true;
document.getElementById("stopped").innerHTML = "Mouse moving";
clearTimeout(timer);
timer = setTimeout(mouseStopped, 500);
});
window.addEventListener("keyup", function() {
buttonPressed = true;
document.getElementById('keyPressed').innerHTML = "Keys Pressed";
clearTimeout(timer);
timer = setTimeout(keyStopped, 500);
});
window.addEventListener("keydown", function() {
buttonPressed = true;
document.getElementById('keyPressed').innerHTML = "Keys Pressed";
clearTimeout(timer);
timer = setTimeout(keyStopped, 500);
});
function checkTime(i) {
if (i < 10) {
i = "0" + i
}; // add zero in front of numbers < 10
return i;
}
window.onload = idleTime;
<div id="stopped"><br>Mouse stopped</br></div>
<div id="keyPressed"> Keys not Pressed</div>
<strong>
<div id="header"><br>Time Idle:</br></div>
<div id="idle"></div>
</strong>
Need some help with my code, I can't get my alerts to work with my countdown timer. They should be alerting at 4,3,2 minutes left on the timer. I currently can't get the alerts to fire at all, sometimes they would fire but each second after 4, the alert for "4" would fire. I need it to just go once... Any help would be appreciated
Heres my script
var running=false
var endTime=null
var timerID=null
function startTimer(){
running=true
now=new Date()
now=now.getTime()
endTime=now+(1000*60*5)
showCountDown()
}
function showCountDown(){
var now=new Date()
now=now.getTime()
if (endTime-now<=239990 && endTime-now>240010){alert("4")};
if (endTime-now<=179990 && endTime-now>180010){alert("3")};
if (endTime-now<=119990 && endTime-now>120010){alert("2")};
if (endTime-now<=0){
stopTimer()
alert("Time is up. Put down pencils")
} else {
var delta=new Date(endTime-now)
var theMin=delta.getMinutes()
var theSec=delta.getSeconds()
var theTime=theMin
theTime+=((theSec<10)?":0" : ":")+theSec
document.forms[0].timerDisplay.value=theTime
if (running){
timeID=setTimeout("showCountDown()",1000)
}
}
}
function stopTimer(){
clearTimeout(timeID)
running=false
document.forms[0].timerDisplay.value="0.00"
}
Update, Sorry meant minutes instead of seconds
Update 2: Change the ifs, now they fire but keep firing after the 4 second mark
if (endTime-now<=240010 && endTime-now<=239990){alert("4")};
if (endTime-now<=180010 && endTime-now<=179990){alert("3")};
if (endTime-now<=120010 && endTime-now<=119990){alert("2")};
Why are you calling clearTimeout? setTimeout invokes its callback only once. There is no need to clear it. Also you could just have a variable that stores the minutes until the end of the countdown and decrement that by one in each iteration.
The simplest solution might look like this
function startTimer(minutesToEnd) {
if(minutesToEnd > 0) {
if(minutesToEnd <= 4) {
console.log(minutesToEnd);
}
setTimeout(startTimer, 60000, minutesToEnd - 1);
} else {
console.log("Time is up. Put down pencils")
}
}
I actually spent some time working on this. I have no idea if this is what you wanted, but I created a timer library. I have a working demo for you. I had fun making this. Let me know what you think:
JS:
(function () {
var t = function (o) {
if (!(this instanceof t)) {
return new t(o);
}
this.target = o.target || null;
this.message = o.message;
this.endMessage = o.endMessage;
//setInterval id
this.si = -1;
//Initial start and end
this.startTime = null;
this.endTime = null;
this.interTime = null;
this.duration = o.duration || 1000 * 60 * 5;
//looping speed miliseconds it is best to put the loop at a faster speed so it doesn't miss out on something
this.loop = o.loop || 300;
//showing results miliseconds
this.show = o.show || 1000;
};
t.fn = t.prototype = {
init: function () {}
};
//exporting
window.t = t;
})();
//Timer Functions ---
t.fn.start = function () {
this.startTime = new Date();
this.interTime = this.startTime.getTime();
this.endTime = new Date().setMilliseconds(this.startTime.getMilliseconds() + this.duration);
//returns undefined... for some reason.
console.log(this.endTime);
var $this = this;
this.writeMessage(this.duration);
this.si = setInterval(function () {
var current = new Date(),
milli = current.getTime();
if (milli - $this.interTime >= $this.show) {
var left = $this.endTime- milli;
if (left <= 0) {
$this.stop();
} else {
$this.interTime = milli;
$this.writeMessage(left);
}
}
}, this.loop);
return this;
};
t.fn.writeMessage = function(left){
this.target.innerHTML = this.message + ' ' + Math.floor(left / 1000);
return this;
};
t.fn.stop = function () {
//stopping the timer
clearInterval(this.si);
this.target.innerHTML = this.endMessage;
return this;
};
//Not chainable
t.fn.isRunning = function () {
return this.timer > -1;
};
var timer = t({
target: document.getElementById('results'),
loop: 50,
duration: 10000,
show: 1000, //default is at 1000 miliseconds
message: 'Time left: ', //If this is ommited then only the time left will be shown
endMessage: 'Time is up. Put down your pencils'
}).start();
document.getElementById('stop').onclick = function(){
timer.stop();
};
HTML:
<div id="results"></div>
<button id="stop">Stop</button>
Demo here
Update: I added some stuff
Demo 2
Update 2: I fixed the bug where 10 would hop straight to 8
Demo 3