I have two asp.net buttons and i want to calculate the time difference in between the clicks of the buttons using JS
Button 1 - Start
Button 2 - Next
First I got the current time on the click of the "start" button in getStartTime() function. and similarly for the second button in getEndTime() function.
For calculating the time difference I use another function calculateDifference() and call the above functions. I want to calculate the difference after the "Next" button click. The problem is getStartTime() is calculating the current time every time. How can
I store the time of button click in a variable and return it to another function?
var startTime, startHour, startMin, startSec, endTime, endHour, endMin, endSec, diffTime, stTime, etTime;
//To Get the click time of Start Button(btnStart_OnClick)
function getStartTime() {
startTime = new Date();
startHour = startTime.getHours();
startMin = startTime.getMinutes();
startSec = startTime.getSeconds();
if (startHour > 0) {
startHour = startHour * 3600;
}
if (startMin > 0) {
startMin = startMin * 60;
}
stTime = startHour + startMin + startSec;
return stTime;
}
//To get the click time of Next Button
function getEndTime() {
endTime = new Date();
endHour = endTime.getHours();
endMin = endTime.getMinutes();
endSec = endTime.getSeconds();
if (endHour > 0) {
endHour = endHour * 3600;
}
if (endMin > 0) {
endMin = endMin * 60;
}
etTime = endHour + endMin + endSec;
return etTime;
}
function calculateDifference() {
var start = getStartTime(); // On calling this function, current date is returned instead of the click time of 'Start' button
var end = getEndTime();
var diff = end - start;
return diff;
}
//Button Next_OnClick
function newTimeLeft() {
var difference = calculateDifference();
var newTimeLeft = 1800 - difference;
if (newTimeLeft > 0) {
javascript_countdown.init(newTimeLeft, 'javascript_countdown_time');
}
}
If you need time differences between two button clicks you better keep track of the two timestamps. Then differentiate between two I guess this should work -
let startTime, endTime;
function getStartTime() {
startTime = new Date().getTime()
}
function getEndTime() {
endTime = new Date().getTime()
}
function calculateDifference() {
return startTime - endTime;
}
Calling calculateDifference() will return the time difference in milliseconds. Rest is up to you.
Hope this helps.
Related
I've 2 date variables in my script, One representing the current time and the other 2 minutes later. My aim is to check both values every minute and trigger a function when current is more or equal than the latter.
Here's my code and for some reason it doesn't execute the doing() function
var current = new Date(Date.now());
var endtime = new Date(Date.now() + 2 * 60 * 1000);
hours = ('0' + endtime.getHours()).slice(-2);
mins = ('0' + endtime.getMinutes()).slice(-2);
secs = ('0' + endtime.getSeconds()).slice(-2);
var gametime = hours + ":" + mins + ":" + secs;
$('#endtime').html(gametime);
var i = setInterval(function () { myFunction(); }, 60000);
function myFunction() {
if (new Date(current) > new Date(endtime)) {
doing();
}
}
function doing() {
var body = $('#alert');
var colors = ['white', 'transparent'];
var currentIndex = 0;
setInterval(function () { light(); }, 400);
function light() {
body.css({
backgroundColor: colors[currentIndex]
});
if (!colors[currentIndex]) {
currentIndex = 0;
} else {
currentIndex++;
}
}
alert("Time's up!");
clearInterval(i);
}
Well, you set current and endtime but neither ever changes, so every time myFunction gets called, the condition evaluates to false and so doing is never called.
I would add an else, that advances current, i.e.:
function myFunction() {
if (new Date(current) > new Date(endtime)) {
doing();
} else {
current = new Date(Date.now())
}
}
This way, eventually, current will become greater than endtime.
Thanks to Konrad Linkowski who told me to update the variables, I updated "Current" time variable inside the interval which solved the issue.
I was creating a webpage and I would like to receive assistance in that. I need a text to popup when the UTCHours and UTCMinutes are equal to specific values. I want something like this. This is like the model , not actual code.
h = utcTime
m = utcminutes
if (h=x and m=y)
{
function myFunction();
}
Surely I wont do everything for you, but here you go. A base to start from.
// The button functionality
const $ = (x) => document.getElementById(x);
$('start').addEventListener('click', ()=>{
startTime();
});
$('stop').addEventListener('click', ()=>{
stopTime();
});
// The timer
// set variables
let date,
start,
stop;
function startTime() {
date = new Date(); // get current date.
start = date.getTime(); // get time from current date
// Just output
document.getElementById("showStart").innerHTML = start;
}
function stopTime() {
date = new Date(); // get current date.
stop = date.getTime(); // get time from current date
// just output
document.getElementById("showStop").innerHTML = stop;
document.getElementById("difference").innerHTML = stop-start;
}
jsfiddle
I was bored so here you go.
// The button functionality
const $ = (x) => document.getElementById(x);
$('setAlert').addEventListener('click', ()=>{
setAlert(3); // alert in x seconds.
});
// set variables
let date,
target,
stop,
interval = 1; // integer.
function setAlert(time) {
date = new Date(); // get current date.
target = date.getTime() + ( (time * 1000) - ((interval * 1000) +1000) ); // sets the time it should alert.
/*
* time -1 because it's a 1s interval, that means when it reaches x = y it will alert 1s later by the next "check". This why you need to subtract 1s.
* (time-1)*1000 is because the getTime returns time in ms not in seconds. You would need to make it setAlert(3000),
* i made it bit easier by multiplying the value by 1000 = ms.
*/
// The loop that checks time
setInterval(function(){ // This function makes the "checking each X ms"
if(stop !== target){ // Check if time was reached.
stopTime(); // Check time
}else{
alert("TIME IS OVER"); // When time is reached do this.
}
}, interval*1000); // Refreshes the time each second.
// Just output
document.getElementById("showTarget").innerHTML = target+(interval*1000); // Because the target time has "minus" in it (line 16) it needs to be added to show the real target time.
}
function stopTime() {
date = new Date(); // get current date.
stop = date.getTime(); // get time from current date
// just output
document.getElementById("showStop").innerHTML = stop;
// document.getElementById("difference").innerHTML = stop-target;
}
jsfiddle v2
function displayAlert(hour,minute){
//create a new Date Object(Current Date and Time)
var date = new Date();
// getUTCHours getUTCMinutes are inbuilt methods
// for getting UTC hour and minute by comparing it with timezone
var utcHour = date.getUTCHours();
var utcMinutes = date.getUTCMinutes();
//display alert when utc hour and minute matches sired time
if(utcHour == hour && utcMinutes == minute){
alert(utcHour + " : " + utcMinutes)
}
}
displayAlert(18,31)
setInterval(function(){
now = new Date();
hours = now.getUTCHours();
mins = now.getUTCMinutes();
executeFunctionIfEqualToDefined(hours, mins);
},60000); // this block will run every 60000 milli seconds i.e 60 seconds =1 min
function executeFunctionIfEqualToDefined(hours, mins){
if(hours === x && mins === y){
//execute your code here
}
}
My 14 yr old son is working on a Science Project looking at reaction time and age. He is setting up a little web app to test people - When a page is loaded a timer starts and there is a delay in a STOP button appearing (4 secs for this example). When they click the stop button, the timer stops.
He's done a great job of coding all of that so far. He is using a piece of JavaScript that he found and has modified it to his needs.
His issue - how to pass the stopped time into a variable and then pass that to another page. He is able to successfully do it if the variable is static ie "Hello."
What is wrong with the function stop(); in this example? He currently gets a [object HTMLSpanElement]
var clsStopwatch = function() {
// Private vars
var startAt = 0; // Time of last start / resume. (0 if not running)
var lapTime = 0; // Time on the clock when last stopped in milliseconds
var now = function() {
return (new Date()).getTime();
};
// Public methods
// Start or resume
this.start = function() {
startAt = startAt ? startAt : now();
};
// Stop or pause
this.stop = function() {
// If running, update elapsed time otherwise keep it
lapTime = startAt ? lapTime + now() - startAt : lapTime;
startAt = 0; // Paused
};
// Reset
this.reset = function() {
lapTime = startAt = 0;
};
// Duration
this.time = function() {
return lapTime + (startAt ? now() - startAt : 0);
};
};
var x = new clsStopwatch();
var $time;
var clocktimer;
function pad(num, size) {
var s = "0000" + num;
return s.substr(s.length - size);
}
function formatTime(time) {
var h = m = s = ms = 0;
var newTime = '';
h = Math.floor( time / (60 * 60 * 1000) );
time = time % (60 * 60 * 1000);
m = Math.floor( time / (60 * 1000) );
time = time % (60 * 1000);
s = Math.floor( time / 1000 );
ms = time % 1000;
newTime = pad(h, 2) + ':' + pad(m, 2) + ':' + pad(s, 2) + ':' + pad(ms, 3);
return newTime;
}
function update() {
$time.innerHTML = formatTime(x.time());
}
function start() {
$time = document.getElementById('time');
update();
clocktimer = setInterval("update()", 1);
x.start();
$(document).ready(function() { $('#mybutton').delay(4000).fadeIn(0);});
}
function stop() {
x.stop();
//var varTime = "Hello";
var varTime = document.getElementById('time');
window.location.href = "somephpfile.php?etime=" + varTime;
}
The var varTime = document.getElementById('time') is assigning the element to the varible, which is fine and not a bad option however I believe your son only needs the HTML text of that element.
There are two options. The first option keeps the time element in the function for possible expansion later.
function stop() {
x.stop();
var varTime = document.getElementById('time');
if (varTime) {
window.location.href = "somephpfile.php?etime=" + varTime.innerHTML;
}
}
Or just extract the required text and send it - even if it is empty.
function stop() {
x.stop();
if (document.getElementById('time')) {
window.location.href = "somephpfile.php?etime=" + document.getElementById('time').innerHTML;
}
}
You need to read the innerHTML of the element instead if just reading element itself. This can be accomplished by :
function stop() {
x.stop();
//var varTime = "Hello";
var varTime = document.getElementById('time').innerHTML;
window.location.href = "somephpfile.php?etime=" +
}
I want to get the time difference in between two clicks on a single button.
I have my markup like this
click here
I am using this code to get the time difference between two clicks.
var clickedTime = '';
var lastClicked = '';
$('body').on('click', 'a', function(e) {
var d = new Date();
clickedTime = lastClicked;
lastClicked = d.getTime();
console.log(clickedTime);
console.log(lastClicked);
});
But its showing the same time in both console. So can someone tell me how to get the time difference?
Here is a simple jQuery function to return the time difference in the desired format for every x clicks - Demo
<button>Get Time Difference</button>
(function ($) {
$.fn.clickTimer = function ($param, $numbClicks) {
function msTotime(ms) {
var mill = ms % 1000;
var seconds = Math.floor((ms / 1000) % 60);
var minutes = Math.floor((ms / (60 * 1000)) % 60);
switch ($param) {
case "ms":
return ms;
break;
case "s":
return seconds;
break;
default:
return [minutes, seconds, mill];
}
}
var counter = 0;
var Start_Time;
this.click(function (event) {
counter++;
if (counter == $numbClicks) {
counter = 0;
var now = event.timeStamp;
Diff = now - Start_Time;
console.log(msTotime(Diff));
} else {
Start_Time = event.timeStamp;
}
});
return this;
};
})(jQuery);
Usage :
$(selector).clickTimer(time format , number of clicks);
$("button").clickTimer("ms", 2);
// returns time difference in milliseconds for every 2 clicks
$("button").clickTimer("s", 2);
// returns time difference in seconds
$("button").clickTimer(false, 2);
// returns an array [minutes, seconds, milliseconds]
Let me know what you think. This is definitely not a perfect solution but it may get you started.
You can use Date.prototype.getTime() to get time of click event.
var click = 0;
var time;
var difference;
$("a").click(function(){
var date = new Date();
click += 1;
if (click == 2) {
difference = date.getTime() - time;
click = 0;
console.log(difference);
}
else
time = date.getTime();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<a>Please double click on me!</a>
Or use Event.timeStamp property of event.
var click = 0;
var time;
var difference;
$("a").click(function(e){
click += 1;
if (click == 2) {
difference = e.timeStamp - time;
click = 0;
console.log(difference);
}
else
time = e.timeStamp;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<a>Please double click on me!</a>
Note that the codes return diffrence time in milisecond.
I'm fairly new to DOM and the whole HTML and PHP Stuff so I'm seeking some information on how to do this. What I have until now is a Javascript. Now I want/have to use DOM to show this script. (FYI: I'm implementing something for Moodle and this has be done like this)
What I have found out about DOM is that I can change values of different Nodes. The problem I've found myself in is that all the examples I found were like. Click on a button and something happens. That's ok but now I want my script to run every second so I can the person who needs it can see that the time is running down.
I hope I gave you enough information and I hope you can help me. Thank you for trying to help me.
var running = false
var endTime = null
var timerID = null
// totalMinutes the amount of minutes is put into
var totalMinutes = 3;
function startTimer() {
// running is being started and the current time is put into the variable
running = true
now = new Date()
now = now.getTime()
// Variable endTime gets the time plus the maximum time
endTime = now + (1000 * 60 * totalMinutes);
showCountDown()
}
function showCountDown() {
// same as startTimer, time is saved in variable now
var now = new Date()
now = now.getTime()
if (endTime - now <= 0) {
// Variable timerID gets clearTimeout -->http://de.selfhtml.org/javascript/objekte/window.htm#clear_timeout
clearTimeout(timerID)
// boolean running set to false
running = false
alert("Ihr Resultat wird nun ausgewertet!")
} else {
// delta is being calculated
var delta = new Date(endTime - now)
var theMin = delta.getMinutes()
var theSec = delta.getSeconds()
var theTime = theMin
// show seconds and minutes
theTime += ((theSec < 10) ? ":0" : ":") + theSec
document.getElementById('CheckResults').innerHTML = " (Übung in " + theTime + " Minuten abgelaufen)"
if (running) {
timerID = setTimeout("showCountDown()",900)
}
}
}
</script>
You might want to use window.setInterval for a start. Here is a short example. Create a blank html page, put the script into the head section, and the markup into the body section. I wasn't able to post it with proper html and body tags
<script>
function countDownTimer(msecGranularity, output) {
var secRunningTime, startTime, endTime, onFinish, interval;
function heartBeat() {
var diff = endTime - new Date();
output.innerHTML = diff / 1000;
if (diff < 0) {
window.clearInterval(interval);
onFinish();
};
};
this.start = function (secRunningTime, finishHandler) {
onFinish = finishHandler;
startTime = new Date();
endTime = startTime.setSeconds(startTime.getSeconds() + secRunningTime);
interval = window.setInterval(heartBeat, msecGranularity);
}
};
function startTimer(duration, granularity) {
var output = document.createElement("div");
document.getElementById("timerOutputs").appendChild(output);
var t = new countDownTimer(granularity, output);
t.start(duration, function () { output.innerHTML = 'TIMER FINISHED' });
};
</script>
In the HTML place these to start the timer class.
<button onclick="startTimer(60,100)">Start a new 60 seconds timer with 100 msec granularity</button><br />
<button onclick="startTimer(600,1000)">Start a new 600 seconds timer with 1000 msec granularity</button>
<div id="timerOutputs">
</div>