I'm trying to make a program that tests your reaction time, but I don't know how to measure the time between two events, like button clicks. Here's my code so far. Thanks in advance to anyone that can help.
<!DOCTPYE html>
<html>
<head>
<script>
var button = document.getElementById("reactionTester");
var start = document.getElementById("start");
function init() {
var startInterval/*in milliseconds*/ = Math.floor(Math.random() * 30) * 1000;
setTimeout(startTimer, startInterval);
}
function startTimer() {
/*start timer and then later use stopTimer() to stop the timer and find
the difference bettween both button clicks.*/
}
</script>
</head>
<body>
<form id="form">
<input type="button" id="reactionTester" onclick="stopTimer()">
<input type="button" value="start" id="start" onclick="init()">
</form>
</body>
</html>
var startTime;
function startButton() {
startTime = Date.now();
}
function stopButton() {
if (startTime) {
var endTime = Date.now();
var difference = endTime - startTime;
alert('Reaction time: ' + difference + ' ms');
startTime = null;
} else {
alert('Click the Start button first');
}
}
Bind your start and stop buttons to these functions.
DEMO
For getting the time that has passed, you'll always need a start_time and end_time. startTimer() should set a start_time variable (or something similarly named), and stopTimer() should set an end_time variable.
stopTimer() can then subtract the two times and you've got the number of milliseconds passed.
(JavaScript stores times in milliseconds, so oldTime - newTime = milliseconds passed.)
Edit: Example JSFiddle - http://jsfiddle.net/L3Xha/
var startTime, endTime;
// self-executing function
(function(){
// init the background to white
document.body.style.background = "white";
// reset the color of the BG after 3 seconds.
setTimeout(
function(){
document.body.style.background = "red";
startTime = Date.now();
}
, 3000);
$("#go").on("click", function(){
stopTime = Date.now();
$("#reflex").text(
"Your time was " + (stopTime - startTime) + "ms."
);
});
})();
Keep track of the time of the first click, and on the second click, display the difference between now and the first click.
var start;
$('button').click(function() {
if (undefined === start) {
start = new Date().getTime();
return;
}
alert('Time difference is:' + (new Date.getTime() - start));
});
To measure millseconds between two button clicks, log timestamps in javascript
First Button:
document.getElementById('submit-button1').onclick = function() {
console.log(new Date().getTime()); //1388696290801
}
Second Button:
document.getElementById('submit-button2').onclick = function() {
console.log(new Date().getTime()); //1388696292730
}
You don't need a form, you just need buttons, you don't need intervals either. You also don't need jQuery.
<!DOCTPYE html>
<html>
<head>
<script>
var startTime, running;
function startStop() {
if (running) {
var timeTaken = Date.now() - startTime;
running = false;
console.log("Time: " + timeTaken);
}
else {
running = true;
startTime = Date.now();
}
}
</script>
</head>
<body>
<button onclick="startStop();">Start/Stop</button>
</body>
</html>
Edit
Date.now() is probably faster.
Related
I have created this stopwatch and it runs pretty well. The only problem that I am having is that whenever I click my "stop" button, the time stops on the screen but it is still running in the background.
Is there any way to stop this from happening? I want the timer to stop on its current time, then when I click "start", it resumes from the time it was stopped on.
Im thinking maybe create a "new Date()" variable before the update function and another "new Date()" variable inside of the update function and somehow subtract those to get the current date. But I cannot figure that out either.
start = document.getElementById('Start');
stop = document.getElementById('Stop');
let watchRunning = false;
Start.addEventListener('click', startHandler);
Stop.addEventListener('click', stopHandler);
function startHandler() {
if (!watchRunning) {
watchRunning = setInterval(update, 70);
}
}
function stopHandler() {
clearInterval(watchRunning);
watchRunning = null;
}
update();
var seconds;
var milliseconds;
var d;
function update() {
d = new Date();
seconds = d.getSeconds();
milliseconds = Math.floor((d.getMilliseconds() / 10));
if (milliseconds < 10 && seconds < 10) {
document.getElementById("Time").innerHTML =
"0" + seconds + ".0" + milliseconds;
} else if (milliseconds < 10 && seconds >= 10) {
document.getElementById("Time").innerHTML =
seconds + ".0" + milliseconds;
} else if (milliseconds >= 0 && seconds < 10) {
document.getElementById("Time").innerHTML =
"0" + seconds + "." + milliseconds;
} else if (milliseconds >= 0 && seconds >= 10) {
document.getElementById("Time").innerHTML =
seconds + "." + milliseconds;
}
}
#Time {
background-color: yellow;
max-width: 2.3%;
}
<h1>Stop Watch</h1>
<button id="Start">Start</button>
<button id="Stop">Stop</button>
<h3>Elapsed Time:</h3>
<p id="Time"></p>
Try running the snippet and you will see what I mean. The time doesn't stop "running" after I click stop, and when I click start it resumes as if it was never stopped.
clearTimeout( return ID of setTimeout() );
clearTime variable is returned as a value by the setTimeout( ) timing method, which can be pass to the clearTimeout( ID ) as an ID to reference it - clearTimeout( clearTime );
How It Works
Whenever the clearTimeout( ) timing method is called on a setTimeout( ) timing method that is active, the clearTimeout( ) timing method will stop the execution of the setTimeout( ) timing method but without destroying its execution entirely.
The setTimeout( ) timing method is left idle during the period that the clearTimeout( ) timing method is called, and when you re-execute the setTimeout( ) timing method, it will start from the point its execution was stopped, not starting all over from the beginning.
You're good to go!
You should use a setInterval to run your code to update the stopwatch instead of relying on a Date; you can not stop the Date from changing, so even though you stopped updating your stopwatch, the seconds are still ticking by which makes it seem like your stopwatch never stopped.
#Time {
background-color: yellow;
max-width: 2.3%;
}
<h1>Stop Watch</h1>
<button id="Start">Start</button>
<button id="Stop">Stop</button>
<h3>Elapsed Time:</h3>
<p id="Time">00:00</p>
<script>
var start = document.getElementById('Start'), stop = document.getElementById('Stop'), time = document.getElementById('Time');
function StopWatch(props){
this.seconds = props.seconds||0;
this.milliseconds = props.milliseconds||0;
this.updateCallback = props.updateCallback;
this._running = false;
}
StopWatch.prototype = {
start: function(){
var _this = this;
if(!_this._running){
_this._running = true;
_this._intervalID = window.setInterval(function(){
if(++_this.milliseconds==100){
_this.seconds++;
_this.milliseconds = 0;
}
if(_this.updateCallback){
_this.updateCallback(_this.milliseconds, _this.seconds);
}
}, 10);
}
},
stop: function(){
window.clearInterval(this._intervalID);
this._running = false;
},
getTimeString: function(){
var ms = this.milliseconds, s = this.seconds;
if(ms<10){
ms = "0"+ms;
}
if(s<10){
s = "0"+s;
}
return s + ":" + ms;
}
}
var sw = new StopWatch({updateCallback: function(){
time.textContent = sw.getTimeString();
}});
start.addEventListener('click', function(){
sw.start();
});
stop.addEventListener('click', function(){
sw.stop();
});
</script>
I am trying to create html5 app that have a timer. After time end in 10 second, it will display a button. Supposed to be, once user click on the button, a popup will displayed and it will count the button click in a variable and reset the timer. The process will loop again. The issue is, after user click on the button, and after the timer finished countdown for second time, the button is not displaying.
Here is the Js codes:
<!-- Timer countdown -->
<script type=text/javascript>
var clicks = 0;
function showTimer(selector, seconds)
{
var startTime = Date.now();
var interval;
function showRemaining()
{
var delta = Date.now() - startTime; // milliseconds
var deltaSeconds = delta / (1000);
if (deltaSeconds < seconds) {
// display minutes remaining
$(selector).text(Math.round(seconds - deltaSeconds));
} else {
$(selector).text(0);
clearInterval(interval);
}
}
interval = setInterval(showRemaining, 1000);
showRemaining();
}
$(document).ready(function()
{
showTimer("#countdown", 10);
});
setTimeout(function()
{
$("#proceed").show();
}, 10000);
//when click button
function onClick() {
clicks += 1;
document.getElementById("proceed").style.visibility="hidden";
alert("Getting the message");
document.getElementById("clicks").innerHTML = clicks;
showTimer("#countdown", 10);
};
</script>
This is the HTML:
<h1>Test</h1>
<br>
<p ><span id="countdown"></span><br>
Timer Here<br>
<button type="button" id="proceed" onclick="onClick()">Click</button><br>
<a id="clicks">0</a></p>
you forget to show your button again, the way you did it , it's going to hide. remove the setTimeout since you know the end of your timer and also can repeat it.
var clicks = 0;
var interval = -1;
function showTimer(selector, seconds)
{
var startTime = Date.now();
function showRemaining()
{
var delta = Date.now() - startTime; // milliseconds
var deltaSeconds = delta / (1000);
if (deltaSeconds < seconds) {
// display minutes remaining
$(selector).text(Math.round(seconds - deltaSeconds));
} else {
$(selector).text(0);
clearInterval(interval);
$("#proceed").show(); // Look at here
}
}
if( interval > -1 ) clearInterval(interval);
interval = setInterval(showRemaining, 1000);
showRemaining();
}
$(function() {
showTimer("#countdown", 10);
});
//when click button
function onClick() {
$("#proceed").hide();
alert("Getting the message");
$("#clicks").text(++clicks);
showTimer("#countdown", 10);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Test</h1>
<br>
<p >
<span id="countdown"></span><br>
Timer Here<br>
<button type="button" id="proceed" onclick="onClick()">Click</button><br>
<a id="clicks">0</a>
</p>
include jquery file link,
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js" type="text/javascript"></script>
I wrote a little browser-game.
The rules are easy: you have 15 seconds to decide if you know the name written on the screen.
You have two buttons: "i know"/"give up" - depends on what you want to choose.
If you choose "give up" (or time ends) photo 1 appears. Otherwise, photo 2 will be shown.
Whole operation is looped.
Here's my question: I wanted to choose random name from array "word" every single round, so I wrote function "random_word()". I put it into "timer()", "surrender()" and "winning()" functions. But it doesn't work.
I'm just starting with programming, so I'll be grateful for possibly easiest to understand code. Thanks for all help.
Here's my code:
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
</head>
<body>
<button id= "btnSurrender">give up</button>
<button id= "btnWinning">i know</button>
<p id="seconds">15</p>
<div id="photo"></div>
<script type="text/javascript">
var word = new Array(3);
word[0] = "Michael";
word[1] = "Simon";
word[2] = "Peter";
word[3] = "Mark";
function random_word(){
var randomWord = word[Math.floor(Math.random()*word.length)]
}
var btn1 = document.getElementById("btnSurrender");
var btn2 = document.getElementById("btnWinning");
var pic = document.getElementById("photo");
var secondsP = document.getElementById('seconds');
var clock = null;
btn1.addEventListener("click", surrender);
btn2.addEventListener("click", winning);
function timer () {
random_word();
clearInterval(clock);
var start = new Date().getTime();
clock = setInterval(function() {
pic.innerHTML='<img src="" alt="">';
var seconds = Math.round(15 - (new Date().getTime() - start) / 1000);
if (seconds >= 0) {
secondsP.textContent = seconds;
} else {
clearInterval(clock);
}
if (seconds === 0) {
pic.innerHTML='<img src="mops bops.png" alt="">';
}
}, 1000);
}
function surrender(){
clearInterval(clock);
pic.innerHTML='<img src="mops bops.png" alt="">';
secondsP.textContent = 0;
setTimeout(timer,2000);
word[Math.floor(Math.random()*word.length)]
random_word();
}
function winning(){
clearInterval(clock);
pic.innerHTML='<img src="mopsik.jpg" alt="">';
secondsP.textContent = 0;
setTimeout(timer,2000);
word[Math.floor(Math.random()*word.length)]
random_word();
}
timer();
document.write(randomWord)
setInterval(timer, 17000)
</script>
</body>
</html>
var randomWord;
You need to arrow it at the beginning of the script, before giving a document.write
When I tested your code and set it to the "randomWord" variable at the beginning of the code, it worked; You should do the same, set the variable at the beginning of the code!
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
There is one button in JavaScript of jQuery. The first time I press the button, after some seconds again I press the same button. I got the code for calculating interval between two clicks of the same button from Stack Overflow. How can I calculate interval between first click and third click of the same button, and first click and fourth click of the same button. Please help.
Code to calculate interval time between first and second click:
var startTime;
$("#bu").on('click', function() {
if(startTime) {
alert( "Time difference: " + (new Date().getTime() - startTime) );
startTime = undefined;
} else {
startTime = new Date().getTime();
}
});
Like this:
var clickTimes = [];
$("#bu").on('click', function() {
var clickTime = new Date().getTime();
for (var i = 0; i < clickTimes.length; i++) {
var difference = clickTime - clickTimes[i];
alert("Time since click " + (i + 1) + ": " + difference);
}
clickTimes.push(clickTime);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="bu" value="Click me"/>
By storing all the times the button was clicked in an array, you can calculate the difference between any two clicks at any point. So for the third and the fourth click, respectively, it would be:
var timeBetweenFirstAndThirdClick = clickTimes[2] - clickTimes[0];
var timeBetweenFirstAndFourthClick = clickTimes[3] - clickTimes[0];
You can push time in array when button is clicked and using that array you can find difference between any clicks.
I guess this is what you meant!
var startTime;
var count1 =1;
$("#bu").on('click', function() {
if(startTime) {
alert( "difference start and "+ count1 +"click: " + (new Date().getTime() - startTime) );
count1++;
} else {
startTime = new Date().getTime();
}
});