If found how to do this thanks to this post, but as you can see by the code bellow I'm trying to console.log('Done'); when the time since the last click is greater than 2 seconds. However this doesn't work.
var lastClick = 0;
var button_pressed = false;
let button1 = document.getElementById('button1');
let button2 = document.getElementById('button2');
button1.onclick = function() {
button_pressed = true;
CheckAnswer();
}
button2.onclick = function() {
button_pressed = true;
CheckAnswer();
}
function CheckAnswer() {
if(button_pressed === true) {
var d = new Date();
var t = d.getTime();
if(t - lastClick < 2000) {
console.log('Continue');
}
} else if (t - lastClick > 2000) {
console.log('Done');
}
lastClick = t;
}
<button id="button1">Button1</button>
<button id="button2">Button2</button>
Thank you for your help.
The code never reaches the else if, because it requires button_pressed to be false
I fixed your code, see below.
The else if is now declared withtin the button_pressed === true statement.
function CheckAnswer() {
if(button_pressed === true) {
var d = new Date();
var t = d.getTime();
if(t - lastClick < 2000) {
console.log('Continue');
} else {
console.log('Done');
}
}
lastClick = t;
}
var lastClick = Date.now();
var button_pressed = false;
let button1 = document.getElementById('button1');
let button2 = document.getElementById('button2');
button1.onclick = function() {
button_pressed = true;
CheckAnswer();
}
button2.onclick = function() {
button_pressed = true;
CheckAnswer();
}
function CheckAnswer() {
var t = Date.now();
var diff = t - lastClick;
if(diff < 2000) {
console.log('Continue');
} else {
console.log('Done');
}
lastClick = t;
}
<button id="button1">Button1</button>
<button id="button2">Button2</button>
Related
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.
function startGame(diff){
if (diff === 'easy'){
loadEasy();
}
}
function loadEasy(){
difficultyPage.style.display = 'none';
game.style.display = 'block';
medHardTemplate.style.display = 'none';
easyTemplate.style.display = 'block';
newGame.addEventListener('click', function(){
changeDifficulty('easy');
});
colors = randomColorsArray(3);
correctColor = colorToChoose(colors);
colorRGB.innerHTML = correctColor;
for (var i = 0; i < easySquares.length; i++) {
//add colors to squares
easySquares[i].style.backgroundColor = colors[i];
easySquares[i].addEventListener('click', function(){
var clickedColor = this.style.backgroundColor;
if(clickedColor === correctColor) {
changeColorsOnWinEasy(correctColor);
message.innerHTML = "Correct!"
again.textContent = "Play Again?"
again.addEventListener('click', function(){
again.textContent = "NEW COLORS";
header.style.backgroundColor = "#232323";
colorRGB.style.backgroundColor = "#232323";
message.innerHTML = "";
changeDifficulty('easy');
});
}
else {
this.style.backgroundColor = "#232323";
message.innerHTML = "Wrong!"
}
});
}
}
I don't know when to return the function so that I don't have many functions running at the same time if I spam the newGame button causing my app to lag. I added a return; at the end of the loadEasy function but that didn't seem to do anything.
You may set a flag indicating the current gametype, then you dont need to rebind a button handler everytime, you just need to define the button as start the current game:
let gametype = "easy":
function startGame(diff){
gametype = diff || gametype;
if (gametype === 'easy'){
loadEasy();
}
else {
throw Error('unknown gametype: ' + gametype);
}
}
function loadEasy(){
//... Whatever
}
newGame.addEventListener('onclick', function(){
startGame();
});
So to start a game with the current gametype do:
startGame();
To start a different one, pass a parameter:
startGame("medium");
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>
I've been bothering on this problem for a while now, I have a timer that has 4 buttons start, stop, reset and lap, when I call Stopwatch.start();, Stopwatch.stop(); or Stopwatch.reset(); it works just fine but when I'm trying to call Stopwatch.lap(); it does not work !
I had the answer before but now I have a new computer and things like that and I can't call the function. The console says "Uncaught TypeError: Stopwatch.lap is not a function" and I can't find the problem.
Here is my code:
var Stopwatch = {
init: function(elem, options) {
var timer = createTimer(),
startButton = createButton("start", start),
stopButton = createButton("stop", stop),
resetButton = createButton("reset", reset),
lapButton = createButton("lap", lap),
lapSpan = createTimer(),
offset,
clock,
interval;
options = options || {};
options.delay = options.delay || 1;
elem.appendChild(timer);
elem.appendChild(startButton);
elem.appendChild(stopButton);
elem.appendChild(resetButton);
elem.appendChild(lapButton);
elem.appendChild(lapSpan);
reset();
function createTimer() {
return document.createElement("span");
}
function createButton(action, handler) {
var a = document.createElement("a");
a.href = "#" + action;
a.innerHTML = action;
a.addEventListener("click", function(event) {
handler();
event.preventDefault();
});
return a;
}
function start() {
if (!interval) {
offset = Date.now();
interval = setInterval(update, options.delay);
}
}
function stop() {
if (interval) {
clearInterval(interval);
interval = null;
}
}
function lap() {
lapSpan.innerHTML=timer.innerHTML;
}
function reset() {
clock = 0;
render(0);
lap();
}
function update() {
clock += delta();
render();
}
function render() {
timer.innerHTML = clock / 1000;
}
function delta() {
var now = Date.now(),
d = now - offset;
offset = now;
return d;
}
this.getTime=function() {
return clock;
}
this.start = start;
this.stop = stop;
this.reset = reset;
}
};
var elems;
window.onload=function() {
elems = document.getElementsByClassName("basic");
for (var i = 0, len = elems.length; i < len; i++) {
Stopwatch.init(elems[i]);
}
}
And I need to call the lap function when I press a specified key and it looks like this:
document.onkeypress = function(e) {
e = e || window.event;
var charCode = e.charCode || e.keyCode,
character = String.fromCharCode(charCode);
if(e.charCode == 98 || e.keyCode == 98) {
Stopwatch.start();
} else if(e.charCode == 114 || e.keyCode == 114) {
Stopwatch.lap();
}
};
I am most familiar with JavaScript and jQuery in this project but I also know HTML and JavaScript.
You did define the function inside the class/object bu you forgot to add this.lap = lap; so you can use it as a method/property.
Should be:
this.start = start;
this.stop = stop;
this.reset = reset;
this.lap = lap; // this one was missing
You need to add
this.lap = lap;
after the lines
this.start = start;
this.stop = stop;
this.reset = reset;
This piece of code works, but I am trying to get the timeout function to reset to '0' every time the button is clicked.
var running = false,
count = 0,
run_for = 700;
var end_counter = function() {
if (running) {
running = false;
$("#status").text("Not Running");
alert(count);
started_at = 0;
}
};
$('button').click(function() {
if (running) {
count++;
} else {
running = true;
$("#status").text("Running");
count = 1;
setTimeout(end_counter, run_for);
}
});
Just cancel and restart it:
var timerId,
count = 0;
function end_counter() {
$("#status").text("Not Running");
alert(count);
count = 0;
}
$('button').click(function() {
$("#status").text("Running");
count++;
clearTimeout(timerId);
timerId = setTimeout(end_counter, 700);
});
var running = false,
count = 0,
run_for = 700;
var timer;
var end_counter = function() {
if (running) {
running = false;
$("#status").text("Not Running");
alert(count);
started_at = 0;
}
};
$('button').click(function() {
clearTimeout(timer);
if (running) {
count++;
timer = setTimeout(end_counter, run_for);
} else {
running = true;
$("#status").text("Running");
count = 1;
timer = setTimeout(end_counter, run_for);
}
});
Set timer to a variable - then clear it on click and restart it after count.