I am using a JavaScript code for a timer which works fine with the code below, the only problem is when i refresh the page one second loses.
I need the timer to keep running even if i refresh the page.
I tried to get local time setHours(00) nothing changed.
How do I keep timer running ?
function work(x, id, id_p) {
var span = document.getElementsByClassName('data-work');
for (i = 0; i < span.length; i++) {
var totalsum = span[i].dataset.totalwork;
}
var Clock = {
totalSeconds: parseInt(x),
totalSecondsproject: parseInt(totalsum),
start: function () {
var self = this;
function pad(val) {
return val > 9 ? val : "0" + val;
}
this.interval = setInterval(function () {
self.totalSeconds += 1;
self.totalSecondsproject += 1;
var hour = pad(Math.floor(self.totalSecondsproject / 3600));
var min = pad(Math.floor(self.totalSecondsproject / 60 % 60));
var sec = pad(parseInt(self.totalSecondsproject % 60));
var totat_work = hour + ":" + min + ":" + sec;
var totat_work_db = self.totalSeconds;
$(".totatl_hour_work").text(totat_work);
$.ajax({
type: 'Post',
url: 'includes/function.php',
data: {divVal: totat_work_db, id_interview: id, id_project:id_p}
});
}, 1000);
}
};
$('.startButton').ready(function () {
Clock.start();
var refresh = setInterval(function () {
$(window).attr('location', 'agent_dashboard.php?autorefresh');
}, 300 * 1000);
});
}
Related
I am using this code for countdown timer to a quiz test. Its working Fine. In this I need to add two buttons one is Pause button and another one is Resume button. When I click a Pause button it's stop time and when I click a Resume button it's start from where I pause the time.
I have tried this code. It's not working.
HTML Code
<div class="div__time">
<div style="display: none;" id="overall_time"></div>
<div id="overall_times"></div>
<div class="total_time"></div>
</div>
<input id="pauseButton" type="button" value="Pause">
<input id="resumeButton" type="button" value="Resume">
JS Code
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js" type="text/javascript"></script>
<script>
var speaking_ms = "00:00:10";
var speaking_ms_arr = speaking_ms.split(":");
var speaking_time_min_sec = (+speaking_ms_arr[0]) * 60 * 60 + (+speaking_ms_arr[1]) * 60 + (+speaking_ms_arr[2]);
var speaking_time_min_sec = parseInt(speaking_time_min_sec) + 1;
var speaking_value;
if (localStorage.getItem("speaking_counter")) {
if (localStorage.getItem("speaking_counter") <= 0) {
speaking_value = speaking_time_min_sec;
} else {
speaking_value = localStorage.getItem("speaking_counter");
}
} else {
speaking_value = speaking_time_min_sec;
}
document.getElementById('overall_time').innerHTML = speaking_value;
var speaking_counter = function() {
if (speaking_value <= 0) {
localStorage.setItem("speaking_counter", speaking_time_min_sec);
} else {
speaking_value = parseInt(speaking_value) - 1;
localStorage.setItem("speaking_counter", speaking_value);
}
document.getElementById('overall_time').innerHTML = speaking_value;
if (speaking_value == 0) {
localStorage.setItem("speaking_counter", speaking_value);
setTimeout(function() {
clearInterval(interval);
}, 1000);
}
var hours = Math.floor(speaking_value / 3600);
var minutes = Math.floor(speaking_value % 3600 / 60);
var seconds = Math.floor(speaking_value % 3600 % 60);
var red_time = hours + ' : ' + minutes + ' : ' + seconds;
document.getElementById('overall_times').innerHTML = red_time;
};
var interval = setInterval(function() {
speaking_counter();
}, 1000);
var Clock = {
pause: function() {
clearInterval(this.interval);
delete this.interval;
},
resume: function() {
if (!this.interval) this.start();
}
};
$('#pauseButton').click(function() { Clock.pause(); });
$('#resumeButton').click(function() { Clock.resume(); });
</script>
Fiddle Link
Thanks in Advance.
I changed the end of the code in the fiddle and it worked: https://jsfiddle.net/bohv0j9w/5/
var Clock = {
pause: function() {
clearInterval(interval);
interval = null;
},
resume: function() {
if (!interval) interval = setInterval(speaking_counter, 1000);
}
};
document.querySelector('#pauseButton').addEventListener("click", Clock.pause);
document.querySelector('#resumeButton').addEventListener("click", Clock.resume);
In your version this.internal is undefined you may want to learn about "this" and scopes in js. And $(...) is a syntax that requires the lib jquery (not included in the fiddle), the vanilla js equivalent is "document.querySelector", you should read the MDN article about this function.
Finally, your syntax is a bit old school. If you use localStorage you aren't targeting very old browsers maybe you should avoid jquery and use keywords such as "const".
Following are your mistakes. (Fiddle link)
var Clock = {
pause: function() {
clearInterval(this.interval);//(this.interval is undefined, replace it with interval)
^^^^
delete this.interval;//(this.interval is undefined, replace it with interval)
^^^^
},
resume: function() {
if (!this.interval) this.start();//(this.interval is undefined, replace it typeof interval === undefined to check whether interval exists or not)
^^^^
^^^^^^^^^^^ //(this.start() is also not defined, replace it with start() and move `var interval = setInterval(fun.....` into new start function)
}
};
look at following code.
var speaking_ms = "00:00:10";
var speaking_ms_arr = speaking_ms.split(":");
var speaking_time_min_sec = (+speaking_ms_arr[0]) * 60 * 60 + (+speaking_ms_arr[1]) * 60 + (+speaking_ms_arr[2]);
var speaking_time_min_sec = parseInt(speaking_time_min_sec) + 1;
var speaking_value;
if (localStorage.getItem("speaking_counter")) {
if (localStorage.getItem("speaking_counter") <= 0) {
speaking_value = speaking_time_min_sec;
} else {
speaking_value = localStorage.getItem("speaking_counter");
}
} else {
speaking_value = speaking_time_min_sec;
}
document.getElementById('overall_time').innerHTML = speaking_value;
var speaking_counter = function() {
if (speaking_value <= 0) {
localStorage.setItem("speaking_counter", speaking_time_min_sec);
} else {
speaking_value = parseInt(speaking_value) - 1;
localStorage.setItem("speaking_counter", speaking_value);
}
document.getElementById('overall_time').innerHTML = speaking_value;
if (speaking_value == 0) {
localStorage.setItem("speaking_counter", speaking_value);
setTimeout(function() {
clearInterval(interval);
}, 1000);
}
var hours = Math.floor(speaking_value / 3600);
var minutes = Math.floor(speaking_value % 3600 / 60);
var seconds = Math.floor(speaking_value % 3600 % 60);
var red_time = hours + ' : ' + minutes + ' : ' + seconds;
document.getElementById('overall_times').innerHTML = red_time;
};
var start = function() {
interval = setInterval(function() {
speaking_counter();
}, 1000);
}
var Clock = {
pause: function() {
clearInterval(interval);
delete interval;
},
resume: function() {
if (typeof interval === 'undefined') start();
}
};
$('#pauseButton').click(function() { Clock.pause(); });
$('#resumeButton').click(function() { Clock.resume(); });
start();
I have fixed your solution and implemented what you were trying to implement. There were minor issues with your solution which i fixed.
1. You were using this to access interval variable that was not part of the clock object in which you were accessing the variable.
2. You were using this.start() function in the resume function of clock object which was not part of the clock object.
3. JQuery used to define events was not included in the fiddle. Although it is included in the code pasted in the question.
html:
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
</head>
<body>
<div class="div__time">
<div style="display: none;" id="overall_time"></div>
<div id="overall_times"></div>
<div class="total_time"></div>
</div>
<input id="pauseButton" type="button" value="Pause">
<input id="resumeButton" type="button" value="Resume">
</body>
js:
var speaking_ms = "00:00:10";
var speaking_ms_arr = speaking_ms.split(":");
var speaking_time_min_sec = (+speaking_ms_arr[0]) * 60 * 60 + (+speaking_ms_arr[1]) * 60 + (+speaking_ms_arr[2]);
var speaking_time_min_sec = parseInt(speaking_time_min_sec) + 1;
var speaking_value;
if (localStorage.getItem("speaking_counter")) {
if (localStorage.getItem("speaking_counter") <= 0) {
speaking_value = speaking_time_min_sec;
} else {
speaking_value = localStorage.getItem("speaking_counter");
}
} else {
speaking_value = speaking_time_min_sec;
}
document.getElementById('overall_time').innerHTML = speaking_value;
var speaking_counter = function() {
if (speaking_value <= 0) {
localStorage.setItem("speaking_counter", speaking_time_min_sec);
} else {
speaking_value = parseInt(speaking_value) - 1;
localStorage.setItem("speaking_counter", speaking_value);
}
document.getElementById('overall_time').innerHTML = speaking_value;
if (speaking_value == 0) {
localStorage.setItem("speaking_counter", speaking_value);
setTimeout(function() {
clearInterval(interval);
}, 1000);
}
var hours = Math.floor(speaking_value / 3600);
var minutes = Math.floor(speaking_value % 3600 / 60);
var seconds = Math.floor(speaking_value % 3600 % 60);
var red_time = hours + ' : ' + minutes + ' : ' + seconds;
document.getElementById('overall_times').innerHTML = red_time;
};
var interval = setInterval(function() {
speaking_counter();
}, 1000);
var Clock = {
pause: function() {
clearInterval(interval);
delete interval;
},
resume: function() {
interval = setInterval(function() {
speaking_counter();
}, 1000);
}
};
$('#pauseButton').click(function() { Clock.pause(); });
$('#resumeButton').click(function() { Clock.resume(); });
Here is the fiddle link: JS Fiddle
You have gotten quite a few answers so far, I wanted to give you another example so that you have an alternative architecture to consider. Definitely read up on scopes and closures and the use of this. Also, you don't need jQuery for this function. Only import a large library like jQuery when you need it. In this case document.getElementById does you well, as does addEventListener.
There are even more exciting ways to handle a countdown (including the use of recursion), but below is an example of envisioning your Clock as a single object. This gives you greater control over the clock and it makes it reusable.
You can define functions on the clock that manage the interval, decrement the countdown, pause, resume, start and reset the clock. I added buttons for each so you can see how it would work. Also note that I commented out localStorage to show that it works without storage, but mainly because the snippets in StackOverflow aren't given permission to use localStorage so it would crash, but you can run this code here as is.
var Clock = {
speaking_value: 10,
interval: -1,
countdown: function() {
speaking_value = this.speaking_value;
if (speaking_value <= 0) {
//localStorage.setItem("speaking_counter", 0);
} else {
speaking_value = parseInt(speaking_value) - 1;
//localStorage.setItem("speaking_counter", speaking_value);
}
document.getElementById('overall_time').innerHTML = speaking_value;
if (speaking_value == 0) {
//localStorage.setItem("speaking_counter", speaking_value);
var self = this;
setTimeout(function() {
clearInterval(self.interval);
}, 1000);
}
this.speaking_value = speaking_value;
this.updateClock();
},
paused: false,
pause: function() {
clearInterval(this.interval);
this.paused = true;
},
resume: function() {
if (this.paused) {
this.paused = false;
this.tick();
}
},
updateClock: function() {
speaking_value = this.speaking_value;
var hours = Math.floor(speaking_value / 3600);
var minutes = Math.floor(speaking_value % 3600 / 60);
var seconds = Math.floor(speaking_value % 3600 % 60);
var red_time = hours + ' : ' + minutes + ' : ' + seconds;
document.getElementById('overall_times').innerHTML = red_time;
},
tick: function() {
var self = this;
this.interval = setInterval(function() {
self.countdown()
}, 1000)
},
start: function() {
this.updateClock();
this.tick();
},
reset: function(){
clearInterval(this.interval);
this.speaking_value = 10;
this.updateClock();
}
};
Clock.updateClock();
document.getElementById('startButton').addEventListener('click', function() { Clock.start(); });
document.getElementById('pauseButton').addEventListener('click', function() { Clock.pause(); });
document.getElementById('resumeButton').addEventListener('click', function() { Clock.resume(); });
document.getElementById('resetButton').addEventListener('click', function() { Clock.reset(); });
<div class="div__time">
<div style="display: none;" id="overall_time"></div>
<div id="overall_times"></div>
<div class="total_time"></div>
</div>
<input id="startButton" type="button" value="Start">
<input id="pauseButton" type="button" value="Pause">
<input id="resumeButton" type="button" value="Resume">
<input id="resetButton" type="button" value="Reset">
I am building an aptitude test with a timer. i want to show a div of time out on countdown finish. and is it possible to show a **Lean Modal Popup ** box on countdown finish. Please help!!!. Heres the code
Javascript
<script language="JavaScript" type="text/javascript">
function CountDownTimer(duration, granularity) {
this.duration = duration;
this.granularity = granularity || 1000;
this.tickFtns = [];
this.running = false;
}
CountDownTimer.prototype.start = function() {
if (this.running) {
return;
}
this.running = true;
var start = Date.now(),
that = this,
diff, obj;
(function timer() {
diff = that.duration - (((Date.now() - start) / 1000) | 0);
if (diff > 0) {
setTimeout(timer, that.granularity);
} else {
diff = 0;
that.running = false;
}
obj = CountDownTimer.parse(diff);
that.tickFtns.forEach(function(ftn) {
ftn.call(this, obj.minutes, obj.seconds);
}, that);
}());
};
CountDownTimer.prototype.onTick = function(ftn) {
if (typeof ftn === 'function') {
this.tickFtns.push(ftn);
}
return this;
};
CountDownTimer.prototype.expired = function() {
return !this.running;
};
CountDownTimer.parse = function(seconds) {
return {
'minutes': (seconds / 60) | 0,
'seconds': (seconds % 60) | 0
};
};
window.onload = function () {
var display = document.querySelector('#time'),
timer = new CountDownTimer(5),
timeObj = CountDownTimer.parse(5);
format(timeObj.minutes, timeObj.seconds);
timer.onTick(format);
document.querySelector('button').addEventListener('click', function () {
timer.start();
});
function format(minutes, seconds) {
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ':' + seconds;
}
if(display.textContent == 0){
document.querySelector("#div1").style.display="block";
}
};
</script>
Html
<button>Start Count Down</button>
<div>Registration closes in <span id="time"></span> minutes!</div>
div to show
<div id="div1" style="display:none;" ><p>Hello</p></div>
Ok, so the thing is, you have this piece of javascript code:
window.onload = function () {
var display = document.querySelector('#time'),
timer = new CountDownTimer(5),
timeObj = CountDownTimer.parse(5);
format(timeObj.minutes, timeObj.seconds);
timer.onTick(format);
document.querySelector('button').addEventListener('click', function () {
timer.start();
});
function format(minutes, seconds) {
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ':' + seconds;
}
if(display.textContent == 0){
document.querySelector("#div1").style.display="block";
}
At the bottom, you have an "if" statement.
Just move that if statement into the "format" function as follow:
window.onload = function () {
var display = document.querySelector('#time'),
timer = new CountDownTimer(5),
timeObj = CountDownTimer.parse(5);
format(timeObj.minutes, timeObj.seconds);
timer.onTick(format);
document.querySelector('button').addEventListener('click', function () {
timer.start();
});
function format(minutes, seconds) {
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ':' + seconds;
console.log(display.textContent);
if(display.textContent == "00:00") {
document.querySelector("#div1").style.display="block";
}
}
};
Your code, the way it currently is, is not performing the check on every tick.
Also, you are not checking against "0". The value should be "00:00"
Of course, you can move the check to show the div into the tick event, but that is totally up to you.
I cant figuret how set cookie for my countdownt timeer, that if i refresh page it vill not disapear but vill counting.
i be glad if eny can help. i use jquery 2.1.4 and this java countdown script, but when i refresh page all my coundown timers are lost!
/**
* Created by op on 18.07.2015.
*/
function leadZero (n)
{
n = parseInt(n);
return (n < 10 ? '0' : '') + n;
}
function startTimer(timer_id) {
var timer = $(timer_id);
var time = timer.html();
var arr = time.split(":");
var h = arr[0];
h = h.split(" / ");
h = h[1];
var m = arr[1];
var s = arr[2];
if (s == 0)
{
if (m == 0)
{
if (h == 0)
{
timer.html('')
return;
}
h--;
m = 60;
}
m--;
s = 59;
}
else
{
s--;
}
timer.html(' / '+leadZero(h)+":"+leadZero(m)+":"+leadZero(s));
setTimeout(function(){startTimer(timer_id)}, 1000);
}
function timer (name, time)
{
var timer_name = name;
var timer = $(timer_name);
var time_left = time;
timer.html(' / '+ time);
startTimer(timer_name);
}
$(document).ready(function(){
$('.fid').click(function (e)
{
var timer_name = '.timer_'+$(this).data('fid');
var timer = $(timer_name);
if (timer.html() == '')
{
var time_left = timer.data('timer');
var hours = leadZero(Math.floor(time_left / 60));
var minutes = leadZero(time_left % 60);
var seconds = '00';
timer.html(' / '+hours+':'+minutes+':'+seconds);
startTimer(timer_name);
}
});
$.each($('.tab'), function () {
$(this).click(function () {
$.each($('.tab'), function() {
$(this).removeClass('active');
});
$(this).addClass('active');
$('.list').hide();
$('#content-'+$(this).attr('id')).show();
});
});
if (window.location.hash != '')
{
var tab = window.location.hash.split('-');
tab = tab[0];
$(tab).click();
}
console.log(window.location.hash)
});
It would help if you actually set a cookie.
Setting the cookie would go like:
document.cookie="timer=" + time;
And then call it at the beginning of your code
var time = getCookie("timer");
The getCookie() function is outlined in that link, as well as a base knowledge about them.
I found a neat timer but I need to customize it a bit to work for my project, I tried to change javascript code so it would be a countdown until the weekend and start again from ex: 6days:23hours:59minutes, but I failed miserably
I also would like to know how possible could I add a third row called days
http://codepen.io/anon/pen/ZYEBjP
JS code
var Clock = (function(){
var exports = function(element) {
this._element = element;
var html = '';
for (var i=0;i<6;i++) {
html += '<span> </span>';
}
this._element.innerHTML = html;
this._slots = this._element.getElementsByTagName('span');
this._tick();
};
exports.prototype = {
_tick:function() {
var time = new Date();
this._update(this._pad(time.getHours()) + this._pad(time.getMinutes()) + this._pad(time.getSeconds()));
var self = this;
setTimeout(function(){
self._tick();
},1000);
},
_pad:function(value) {
return ('0' + value).slice(-2);
},
_update:function(timeString) {
var i=0,l=this._slots.length,value,slot,now;
for (;i<l;i++) {
value = timeString.charAt(i);
slot = this._slots[i];
now = slot.dataset.now;
if (!now) {
slot.dataset.now = value;
slot.dataset.old = value;
continue;
}
if (now !== value) {
this._flip(slot,value);
}
}
},
_flip:function(slot,value) {
// setup new state
slot.classList.remove('flip');
slot.dataset.old = slot.dataset.now;
slot.dataset.now = value;
// force dom reflow
slot.offsetLeft;
// start flippin
slot.classList.add('flip');
}
};
return exports;
}());
var i=0,clocks = document.querySelectorAll('.clock'),l=clocks.length;
for (;i<l;i++) {
new Clock(clocks[i]);
}
I would create a helper:
var TimeHelper = function(days, hours, minutes, callback) {
this.subtractMinute = function() {
minutes = (minutes + 60 - 1) % 60;
if (minutes === 0) {
hours = (hours + 60 - 1) % 60;
if (hours === 0) {
days = (days + 24 - 1) % 24;
if (days === 0) {
days = 24;
hours = 0;
minutes = 0;
}
}
}
callback(days, hours, minutes);
}
}
function refreshUI(days, hours, minutes) {
//refresh my ui elements
}
var timeHelper = new TimeHelper(24, 0, 0);
And then you can call timeHelper.subtractMinute once/minute this on every minute
I have created a simple countdown timer, that counts down the total seconds inputted.
http://jsfiddle.net/tmyie/cf3Hd/
However, I am unsure how to turn 3 minutes (the number entered) into seconds with a format like 1:79, 1:78, etc.
$('.click').click(function () {
var rawAmount = $('input').val();
var cleanAmount = parseInt(rawAmount);
var totalAmount = cleanAmount * 60
$('input').val(" ");
var loop, theFunction = function () {
totalAmount--;
if (totalAmount == 0) {
clearInterval(loop);
}
$('p').text(totalAmount);
};
var loop = setInterval(theFunction, 1000);
})
Any help would be great.
This will show the time like 2:59, 2:58, 2:57, and so on...
1:79, 1:78 isn't a valid time, since a minute has 60 seconds.
Here's the fiddle:
$('.click').click(function () {
var rawAmount = $('input').val();
var cleanAmount = parseInt(rawAmount);
var totalAmount = cleanAmount * 60;
$('input').val(" ");
var loop, theFunction = function () {
totalAmount--;
if (totalAmount == 0) {
clearInterval(loop);
}
var minutes = parseInt(totalAmount/60);
var seconds = parseInt(totalAmount%60);
if(seconds < 10)
seconds = "0"+seconds;
$('p').text(minutes + ":" + seconds);
};
var loop = setInterval(theFunction, 1000);
})
try this code
$('.click').click(function () {
var rawAmount = $('input').val().split(':');
var showTime;
var cleanAmount = ((parseInt(rawAmount[0])*60) +parseInt(rawAmount[1]));
$('input').val(" ");
var loop, theFunction = function () {
cleanAmount--;
if (cleanAmount == 0) {
clearInterval(loop);
}
var minutes="0";
var seconds ="0";
if(cleanAmount >60){
minutes = parseInt(cleanAmount/60);
seconds = parseInt(cleanAmount%60);
}
else{
seconds = cleanAmount;
minutes ="0";
}
if(seconds<10)
seconds = "0"+seconds;
$('p').text(minutes+':'+seconds);
};
var loop = setInterval(theFunction, 1000);
});