jQuery time count - javascript

Here's the scenario, I have a time that counts the time_taken by a user. What I want is to get the exact time_taken based from the timer. For example, a user take an exam, then after he/she take the exam, the time_taken will be submitted (e.g. 1hr 25mins 23secs). Please see my code below.
$(document).ready(function(){
var d;
setInterval(function(){
d = new Date();
dates = d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
$('#timeTaken').val(dates);
}, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="timeTaken" value="">

Here is Fiddle for the solution
https://jsfiddle.net/djzsddz6/1/
Ans Solution is below:
$(document).ready(function(){
var seconds = 0, minutes = 0 , hours = 0;
setInterval(function(){
seconds++;
if(seconds == 60){
minutes++
seconds = 0;
}
if(minutes == 60){
hours++
minutes = 0;
}
console.log(hours, minutes, seconds);
$('#timeTaken').val(`${hours}:${minutes}:${seconds}`);
}, 1000);
});

I don't really see the point to use an input there, you can just display in a span and when the form gets submitted take the time elapsed and send it with other data. Anyways, this should work for you:
$(document).ready(function () {
var time_start = new Date();
setInterval(function () {
var time_end = new Date();
var time_diff = (time_end - time_start);
// hours
var hours = Math.floor(time_diff / 1000 / 60 / 60);
// minutes
time_diff = time_diff - hours * 1000 * 60 * 60;
var minutes = Math.floor(time_diff / 1000 / 60);
// seconds
time_diff = time_diff - minutes * 1000 * 60;
var seconds = Math.floor(time_diff / 1000);
renderTime(hours, minutes, seconds);
}, 1000);
});
function renderTime (hrs, min, sec) {
var str = convertTime(hrs) + ":" + convertTime(min) + ":" + convertTime(sec);
$("#timeTaken").val(str);
}
function convertTime (val) {
return val < 10 ? "0" + val : val;
}
What's going on here is we have the time_start which does not change and we have setInterval function that is triggered every second. There we create new Date object, and the subtract the static one from it, which returns the time difference in milliseconds. We do the weird Math.flooring and subtracting, so we can have hours, minutes and seconds as an integers (not floats). Then we use render function to display the time inside an desired element.
Why I think it's a better solution then the others are, is that if you want to handle the user's page refresh you just need to save one variable to cookie or something else and it will work regardless of the page refresh.
Handling the page refresh would look like (with cookie saved for 2 hrs):
function updateTimeCookie () {
var time_now = new Date()
var value = JSON.stringify(time_now);
var expires = time_now.setTime(time_now.getTime() + 7200);
$.cookie("timeStart", value, { expires: expires });
};
// to get Date object from cookie: new Date(JSON.parse($.cookie("timeStart")))
To use $.cookie() you must first include jQuery Cookie Plugin.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
Working fiddle without cookie: https://jsfiddle.net/qc3axmf4/1/
Working fiddle with cookie: https://jsfiddle.net/ta8bnzs0/2/

Rather than getting date at every second you can keep the counter in set interval which will updated at every second. At the time of submission you can perform division and modulus operation to get exact time taken
Example
$(document).ready(function(){
var timer =0;
setInterval(function(){
Timer +=1;
// Code for display in hr mm and ss
$('#timeTaken').val(dates);
}, 1000'
});
You can also convert second in time valueby using moment.js
Hope this helps you.
Happy coding

Related

Reset Timer every x minutes/hour

I am trying two create to separate timers. One timer counts down to a date and displays a countdown and the other counts down on an interval and resets (ie: 5 hours and resets).
The one I am having trouble with is the second option. I am trying to create a countdown that is relative to real-time and then resets once it reaches zero. So for example setting it to 2 days and 5 hours. Once this completes the clock resets to 2 days 5 hours. I am having trouble getting the clock to reset at the specified time and loop without having negative numbers. I tried this two separate ways but feel like I am over-complicating things.
The reason I use real-time is so that the clock will be the same if you open it in another tab. If I create a regular timer it will reset upon refreshing the page.
codpen
In this example I tried to reset the counter every 40 seconds but couldn't get it to work. Ultimately I want to be able to specify the date with ie: 00:12:00 (12 hours countdown) and then have it reset automatically. I just can't figure out how to maintain the counting without going to negative numbers or freezing it.
function timer() {
var currentTime = new Date()
var date = currentTime.getDate()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var seconds = currentTime.getSeconds()
var daysLeft = 0;
var hoursLeft = 24 - hours;
var minsLeft = 60 - minutes;
var secsLeft = 60 - seconds;
// counter freezes at 40 seconds and hangs for 20seconds
if(secsLeft => 40) {
secsLeft = 40 - seconds
if(secsLeft < 0) {
secsLeft = 40
}
}
document.getElementById('timerUpFront').innerHTML= "<br><br><strong>Duration Countdown with Infinite Reset #2</strong><br>" + daysLeft + " days " + hoursLeft + " hours " + minsLeft + " minutes " + secsLeft + " seconds";
}
var countdownTimer = setInterval('timer()', 1000);
codpen
you can separate the timer to functions to simplify it and apply the following logic
function startTimer () {
val targetRemainedSeconds = // calculate the value
val remainedSeconds = targetRemainedSeconds
setInterval(timer(), 1000)
}
function timer () {
remainedSeconds--
if (remainedSeconds < 0) reaminedSeconds = targetReaminedSeconds // reset the timer
timerUpdate()
}
function timerUpdate() {
// use 'remainedSeconds' to update timer
}

Real Time decreasing value in php

I need some advice and logic in my problem.
So, I have an entrydate, from database, then the running current date, and a value of 10(double type in database). So, I know how to calculate the diff of the entrydate and current date, right. So I convert it to seconds then to a number(9.23165).
|Entry |Current Date|Diff(in number)|
|2:00:00 PM |2:30:00 PM | 5.00(Sample)|(First User)
So basically, as current date goes on, can PHP show the deduction on real time? Or I need to refresh? What I need is for it to display the deduction without refreshing. So basically, I need to know what I have to do. Maybe javascipt and ajax?
What you would need are a few Javascript/jQuery functions to update the browser in real time.
var myTimer;
var startTime;
function startTimer() {
stopTimer(); // Reset
startTime = new Date(); // Save to calculate difference
myTimer = setInterval(clockTicking, 1000);
}
function stopTimer() {
clearInterval(myTimer);
}
function clockTicking() {
var now = new Date();
var timeDiff = new Date(now - startTime); // constructor uses UTC, so use UTC date functions from here on
var hours = (timeDiff.getUTCHours() < 10) ? '0' + timeDiff.getUTCHours() : timeDiff.getUTCHours();
var mins = (timeDiff.getUTCMinutes() < 10) ? '0' + timeDiff.getUTCMinutes() : timeDiff.getUTCMinutes();
var secs = (timeDiff.getUTCSeconds() < 10) ? '0' + timeDiff.getUTCSeconds() : timeDiff.getUTCSeconds();
$("<element-where-you-display>").html(hours + ':' + mins + ':' + secs);
}
In Javascript you can call startTimer() to kick it off.

Javascript countdown code

I've a problem when running this script for my JavaScript countdown (using this plugin). What it should do is take the starting time, the current time and the end time and display the remaining time.
If I set these values with normal numbers in epoch time everything works just fine, but my question is: How do I set the current time and the start to be the real current one so that the countdown will be dynamic?
I've found this line: Math.round(new Date().getTime()/1000.0);
But I don't know how to make it work, considering I'm running this script at the bottom of my HTML file, before the </html> tag.
This is the script:
<script>
$('.countdown').final_countdown({
start: '[amount Of Time]',
end: '[amount Of Time]',
now: '[amount Of Time]'
});
</script>
This is how I tried to solve it, but it's not working:
//get the current time in unix timestamp seconds
var seconds = Math.round(new Date().getTime()/1000.0);
var endTime = '1388461320';
$('.countdown').final_countdown({
start: '1362139200',
end: endTime,
now: seconds
});
It sounds like you would like to count down from the current time to some fixed point in the future.
The following example counts down and displays the time remaining from now (whenever now might be) to some random time stamp within the next minute.
function startTimer(futureTimeStamp, display) {
var diff;
(function timer() {
// how many seconds are between now and when the count down should end
diff = (futureTimeStamp - Date.now() / 1000) | 0;
if (diff >= 0) {
display(diff);
setTimeout(timer, 1000);
}
}());
}
// wait for the page to load.
window.onload = function() {
var element = document.querySelector('#time'),
now = Date.now() / 1000,
// some random time within the next minute
futureTimeStamp = Math.floor(now + (Math.random() * 60));
// format the display however you wish.
function display(diff) {
var minutes = (diff / 60) | 0,
seconds = (diff % 60) | 0;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
element.innerHTML = minutes + ":" + seconds;
}
startTimer(futureTimeStamp, display);
};
<span id="time"></span>
Also Math.round(new Date().getTime()/1000.0); will give you the number of seconds since the epoch, however it may be a little disingenuous to round the number. I think you would be better served by taking the floor:
var timestamp = Math.floor(Date.now() / 1000)); is probably a better option.
In addition I am not sure why you need the start time, current time and end time. In order to find the remaining number of second you just need to know when the timer should end and the current time.

Javascript timer just for minutes and seconds

I found a JSFiddle with a timer that counts up every second.
Except i want this to work with just the minutes and seconds. No hours.
Any ideas?
DATE_OBJ.getSeconds() to get seconds of Date object.
DATE_OBJ. getMinutes() to get minutes of Date object.
setInterval to invoke handler function after every second(1000ms).
var handler = function() {
var date = new Date();
var sec = date.getSeconds();
var min = date.getMinutes();
document.getElementById("time").textContent = (min < 10 ? "0" + min : min) + ":" + (sec < 10 ? "0" + sec : sec);
};
setInterval(handler, 1000);
handler();
<h1 id="time" style="text-align: center"></h1>
Here's a very hackish approach - http://jsfiddle.net/gPrwW/1/
HTML -
<div id="worked">31:14</div>
JS :
$(document).ready(function (e) {
var $worked = $("#worked");
function update() {
var myTime = $worked.html();
var ss = myTime.split(":");
var dt = new Date();
dt.setHours(0);
dt.setMinutes(ss[0]);
dt.setSeconds(ss[1]);
var dt2 = new Date(dt.valueOf() + 1000);
var temp = dt2.toTimeString().split(" ");
var ts = temp[0].split(":");
$worked.html(ts[1]+":"+ts[2]);
setTimeout(update, 1000);
}
setTimeout(update, 1000);
});
The precise way of handling this is the following:
store the time of the start of the script
in a function that gets called repeatedly get the time elapsed
convert the elapsed time in whatever format you want and show it
Sample code:
var initialTime = Date.now();
function checkTime(){
var timeDifference = Date.now() - initialTime;
var formatted = convertTime(timeDifference);
document.getElementById('time').innerHTML = '' + formatted;
}
function convertTime(miliseconds) {
var totalSeconds = Math.floor(miliseconds/1000);
var minutes = Math.floor(totalSeconds/60);
var seconds = totalSeconds - minutes * 60;
return minutes + ':' + seconds;
}
window.setInterval(checkTime, 100);
You can easily change the granularity of checking the time (currently set at 0.1 seconds). This timer has the advantage that it will never be out of sync when it updates.
You can make a function that increments a counter every time it's called, shows the value as:
counter/60 minutes, counter%60 seconds
Then you can use the setInterval function to make JavaScript call your code every second. It's not extremely precise, but it's good enough for simple timers.
var initialTime = Date.now();
function checkTime(){
var timeDifference = Date.now() - initialTime;
var formatted = convertTime(timeDifference);
document.getElementById('time').innerHTML = '' + formatted;
}
function convertTime(miliseconds) {
var totalSeconds = Math.floor(miliseconds/1000);
var minutes = Math.floor(totalSeconds/60);
var seconds = totalSeconds - minutes * 60;
return minutes + ':' + seconds;
}
window.setInterval(checkTime, 100);
This might be something?
plain count up timer in javascript
It is based on the setInterval method
setInterval(setTime, 1000);

How can I make a 10 second countdown timer before a download button link appears?

On a download page, I would like to have it so that when the page loads, a 10 second timer automatically starts. On the page, I would like some text to say something like "You can begin your download in 10 seconds..." Then, after the time is up a download button appears for people to click on and start their download.
How can I do this, and what code do I use to include it into a page?
See: http://jsfiddle.net/rATW7/
It's backwards-compatible and not so secure, but 10 seconds isn't much to worry about anyways.
You can use setInterval() to do this.
Note that make sure the countdownElement has an existing text node, which can be any whitespace. If you can't guarantee that, just use innerHTML or innerText/textContent.
window.onload = function() {
var countdownElement = document.getElementById('countdown'),
downloadButton = document.getElementById('download'),
seconds = 10,
second = 0,
interval;
downloadButton.style.display = 'none';
interval = setInterval(function() {
countdownElement.firstChild.data = 'You can start your download in ' + (seconds - second) + ' seconds';
if (second >= seconds) {
downloadButton.style.display = 'block';
clearInterval(interval);
}
second++;
}, 1000);
}
jsFiddle.
Noone could ensure that your intervals are exact, especially if tab (or browser) is inactive (see e.g. this post), so it's better to rely on time difference instead of counter:
var sTime = new Date().getTime();
var countDown = 30;
function UpdateTime() {
var cTime = new Date().getTime();
var diff = cTime - sTime;
var seconds = countDown - Math.floor(diff / 1000);
//show seconds
}
UpdateTime();
var counter = setInterval(UpdateTime, 500);
The working fiddle
A modification of the Fiddle provided by Yuriy which does NOT use JQuery, and works with hours as well if the # of seconds are large enough.
<div id="countdowntimertxt" class="countdowntimer">00:00:00</div>
<script type="text/javascript">
var sTime = new Date().getTime();
var countDown = 3700; // Number of seconds to count down from.
function UpdateCountDownTime() {
var cTime = new Date().getTime();
var diff = cTime - sTime;
var timeStr = '';
var seconds = countDown - Math.floor(diff / 1000);
if (seconds >= 0) {
var hours = Math.floor(seconds / 3600);
var minutes = Math.floor( (seconds-(hours*3600)) / 60);
seconds -= (hours*3600) + (minutes*60);
if( hours < 10 ){
timeStr = "0" + hours;
}else{
timeStr = hours;
}
if( minutes < 10 ){
timeStr = timeStr + ":0" + minutes;
}else{
timeStr = timeStr + ":" + minutes;
}
if( seconds < 10){
timeStr = timeStr + ":0" + seconds;
}else{
timeStr = timeStr + ":" + seconds;
}
document.getElementById("countdowntimertxt").innerHTML = timeStr;
}else{
document.getElementById("countdowntimertxt").style.display="none";
clearInterval(counter);
}
}
UpdateCountDownTime();
var counter = setInterval(UpdateCountDownTime, 500);
</script>
I was writing a reply with code, but alex's reply is better than my quick & dirty solution.
Take into account that if you want to do something like what Rapidshare and others do, you will have to generate the link at the server side and retrieve it with AJAX, otherwise the only thing whoever wants to get the download immediately needs to do is to see the source code of your page ;-)
This is very simple, yes you can make it very easily. Here's the live link, where you can find the codding for making countdown timer , before download link appears : http://www.makingdifferent.com/make-countdown-timer-download-button-link-appears/
Cheers !!
You can use setTimeout function of javascript :
// make the button not visible
setTimeout(()=>{
// here make button visible and clickable
},10000)
// here 10000 -> 10 seconds timeout

Categories