Java Script Calculating and Displaying Idle Time - javascript

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>

Related

The element will not take a textContent input

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;
}

Alert returning as undefined

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.

localStorage how to save countdown value so it wont reset when I reload the page

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);

Pomodoro Clock's time doesn't work

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.

unable to call jquery function one after another

My app looks like this:
Here is the fiddle what I tried. I want to play the next exercise time automatically on the end of the current exercise timer But currently in this fiddle its asking to click the play button for starting the new exercise timer.
Also, I want to play the 5 sounds count saying(1,2,3,4,5) just after the first audio i.e audiosource .
Here is my code:
function myApp($tier) {
this.paused = false;
this.paused = true // set pause to true (stop)
this.isactive = false; // countdown is active
this.timer = $tier;
return this.observer(); // call and return the "observer" method of the "myApp" class
}
myApp.prototype.observer = function() { // observer method
var self = this; // set this to self (this is the current instance of this class)
$('#btn_start').on('click', function(event){ // where an user click on "btn_start"
event.preventDefault();
self.play('mp3'); // call the play method and store the state in a public var
self.countdown(self.onEnd); // 30 is the audio duration - second parameter is the callback when the audio is finished
self.isactive = true;
});
return this; // return this instance
};
myApp.prototype.play = function() { // play method
var song = document.getElementById('audiosource');
if (this.paused === true)
{
console.log('play song'); $("#btn_start").addClass('btn-pause');
song.play();
this.paused = false;
}
else
{
console.log('pause song');$("#btn_start").removeClass('btn-pause');
song.pause();
this.paused = true;
}
return this;
};
myApp.prototype.countdown = function(callback) { // countdown method
var self = this, // class instance
countdown = null, // countdown
ctx = null; // setIntervall clearer
if (this.isactive === true) // if this method yet called
{
return false;
}
countdown = function() {
console.log('start countdown:' + self.paused);
if (self.timer === 0)
{
clearInterval(ctx);
callback.call(this);
return false;
}
if (self.paused === false) // if not in pause
{
self.timer -= 1;
console.log(self.timer);
var msec=rectime(self.timer);
$('#timer > span').html(msec);
}
};
ctx = setInterval(countdown, 1000);
};
myApp.prototype.onEnd = function() {
// when the audio is finish..
$("#btn_start").removeClass('btn-pause');
alert ('end of the first exercise, NOw lets play the second exercise for your with another by loading its time');
new myApp('10');
$('#timer > span').html(rectime('10'));
};
$(function() {
new myApp('4');
$('#timer > span').html(rectime('4'));
});
function rectime(secs) {
var hr = Math.floor(secs / 3600);
var min = Math.floor((secs - (hr * 3600))/60);
var sec = secs - (hr * 3600) - (min * 60);
while (min.length < 2) {min = '0' + min;}
while (sec.length < 2) {sec = '0' + min;}
if (hr) hr += ':';
return hr + min + ':' + sec;
}

Categories