Countdown It does not Work on a minute system - javascript

I have a simple code but there is a problem
How do I make this code work in a minute and a second system
Tried but only work a second!
You can look at the code
https://jsfiddle.net/o183pdqg/1/
I hope for help because I am really tired and I am looking for a solution
function secondPassed() {
var seconds = 120;
var countdownElement = document.getElementById('countdown');
var contentElement = document.getElementById('content');
var adsElement = document.getElementById('ads');
var minutes = Math.round((seconds - 30) / 60);
var remainingSeconds = seconds;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "";
} else {
seconds--;
}
adsElement.style.display = '';
countdownElement.innerHTML = remainingSeconds;
var interval = setInterval(function() {
countdownElement.innerHTML = --remainingSeconds;
if (remainingSeconds === 0) {
clearInterval(interval);
contentElement.style.display = '';
adsElement.style.display = 'none';
}
}, 1000);
}
<div id="container">
Send Code
<div id="ads" style="display: none">
<div id="countdown"></div>
<div>Sent!</div>
</div>
<div id="content" style="display: none">Error!</div>
</div>

you need to put variable minutes and seconds within setInterval function to make it work. Convert the time var remainingSeconds = seconds * 1000; from second to milisecond so it will make it easier when working with new Date().getTime().
To get minutes and second, try it using modulus (%) operator to get remaining time from your starting time.
var availability = true
function secondPassed() {
if (!availability) {
return false
}
var seconds = 120;
var countdownElement = document.getElementById('countdown');
var contentElement = document.getElementById('content');
var adsElement = document.getElementById('ads');
availability = false
adsElement.style.display = '';
contentElement.style.display = 'none';
function runInterval () {
var remainingSeconds = seconds * 1000;
let minutes = Math.floor(remainingSeconds % (1000*60*60)/ (1000*60));
let seconds1 = Math.floor(remainingSeconds % (1000*60) / 1000);
if (seconds1 < 10) {
seconds1 = "0" + seconds1;
}
document.getElementById('countdown').innerHTML = minutes + ":" + seconds1;
if (seconds == 0) {
// clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "";
} else {
seconds--;
}
if (remainingSeconds === 0) {
clearInterval(interval);
contentElement.style.display = '';
adsElement.style.display = 'none';
availability = true
}
}
var interval = setInterval(function() {
// countdownElement.innerHTML = --remainingSeconds;
runInterval ()
}, 1000);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div id="container">
Send Code
<div id="ads" style="display: none">
<div id="countdown"></div>
<div>Sent!</div>
</div>
<div id="content" style="display: none">Error!</div>
</div>
</body>
</html>

You can try with this answer
secondPassed = () => {
let remainingSeconds = 120;
const countdownElement = document.getElementById('countdown');
const contentElement = document.getElementById('content');
const adsElement = document.getElementById('ads');
adsElement.style.display = '';
const getPad = (num) => {
return (num < 10) ? '0' + num.toString() : num.toString();
}
const interval = setInterval(() => {
let minutes = Math.floor(remainingSeconds / 60) % 60;
let seconds = getPad(remainingSeconds % 60);
countdownElement.innerHTML = `${minutes} : ${seconds}`;
remainingSeconds--;
if (remainingSeconds == 0) {
clearInterval(interval);
contentElement.style.display = '';
adsElement.style.display = 'none';
}
}, 1000);
}

Related

Stopping timer at end of block using javascript

I am new to this. I have a Qaultrics survey consisting of different blocks; each block with its own timer. What I want to achieve is the following; if participants complete the first block before the given time, the timer on that block will be cleared as they move to the next block where a new timer would start. In the following block, a new timer needs to start.
Any assistance would be greatly appreciated.
Qualtrics.SurveyEngine.addOnload(function()
{
var headerCont = document.createElement("div");
headerCont.className = "header-cont";
headerCont.id = "header_container";
var header = document.createElement("div");
header.className = "header"
header.id = "header_1";
var timer = document.createElement("div");
timer.className = "timer";
timer.id = "timer_1";
timer.innerHTML = "Time Remaining: <span id='time'>01:00</span>";
headerCont.appendChild(header);
header.appendChild(timer);
document.body.insertBefore(headerCont, document.body.firstChild);
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
var myTimer = setInterval(function() {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
var text = ('innerText' in display)? 'innerText' : 'textContent';
display[text] = minutes + ":" + seconds;
if (--timer < 0) {
clearInterval(myTimer);
timeOver();
}
}, 1000);
}
var timerSeconds = 60,
display = document.querySelector('#time');
startTimer(timerSeconds, display);
var timeOver = function() {
document.getElementById("timer_1").innerHTML = "";}
});
Qualtrics.SurveyEngine.addOnUnload(function()
{
clearInterval(myTimer);
clearInterval(timer);
clearInterval(timer_1);
document.getElementById("timer_1").innerHTML = "";
});
Here is what I did;
On the first question I used the following code
```Qualtrics.SurveyEngine.addOnload(function()
{
var headerCont = document.createElement("div");
headerCont.className = "header-cont";
headerCont.id = "header_container";
var header = document.createElement("div");
header.className = "header"
header.id = "header_1";
var timer = document.createElement("div");
timer.className = "timer";
timer.id = "timer_1";
timer.innerHTML = "Time Remaining: <span id='time'>02:10</span>";
headerCont.appendChild(header);
header.appendChild(timer);
document.body.insertBefore(headerCont, document.body.firstChild);
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
var myTimer = setInterval(function() {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
var text = ('innerText' in display)? 'innerText' : 'textContent';
display[text] = minutes + ":" + seconds;
if (--timer < 0) {
clearInterval(myTimer);
timeOver();
}
}, 1000);
}
var timerSeconds = 130,
display = document.querySelector('#time');
startTimer(timerSeconds, display);
var timeOver = function() {
document.getElementById("timer_1").innerHTML = "";}
});```
Then in the last question in the block, I used the following code
{
Qualtrics.SurveyEngine.addOnPageSubmit(function() {
Qualtrics.SurveyEngine.setEmbeddedData('timeRemaining',timer);
clearInterval(myTimer); // fairly certain this isn't doing anything
});
});
Qualtrics.SurveyEngine.addOnReady(function()
{
/*Place your JavaScript here to run when the page is fully displayed*/
});
Qualtrics.SurveyEngine.addOnUnload(function() {
document.getElementById("header_container").remove();
});```

How can I modify my function to be able to cancel the interval from anywhere in the controller

I am trying to create a countdown and I want to be able to cancel the interval not only when reach 0 but with clicking of a button as well.How can I modify my function to be able to cancel the interval from anywhere in the controller.
function countDown(total) {
total = total * 60;
var interval = $interval(function () {
var minutes = Math.floor(total / 60);
var seconds = total - minutes * 60;
if (minutes < 1)
{
minutes = '0:';
}
else
{
minutes = minutes + ':';
}
if (seconds < 10)
{
seconds = '0' + seconds;
}
self.remainingTime = "Remaining time: " + minutes + seconds;
total--;
if(minutes === '0:' && seconds === '00')
{
$interval.cancel(interval);
}
}, 1000);
}
As suggested by other users, you should make interval global in the controller. Then on the other functions you want to cancel the interval you can call it safely.
Take a look at the below sample:
angular.module('app', [])
.controller('ctrl', function($interval) {
var self = this;
var interval;
self.wizard = {
startInterval: startInterval,
cancelInterval: cancelInterval
};
startInterval();
return self.wizard;
function startInterval() {
countDown(24);
}
function cancelInterval() {
$interval.cancel(interval);
}
function countDown(total) {
cancelInterval();
total = total * 60;
interval = $interval(function() {
var minutes = Math.floor(total / 60);
var seconds = total - minutes * 60;
if (minutes < 1) {
minutes = '0:';
} else {
minutes = minutes + ':';
}
if (seconds < 10) {
seconds = '0' + seconds;
}
self.wizard.remainingTime = "Remaining time: " + minutes + seconds;
total--;
if (minutes === '0:' && seconds === '00') {
$interval.cancel(interval);
}
}, 1000);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<span ng-app="app" ng-controller="ctrl as ctrl">
<span ng-bind="ctrl.remainingTime"> </span>
<br/>
Cancel Interval
<br/>
Start Interval
</span>
I created an example using self instead of $scope like you are in your snippet above. As others mentioned moving the interval var to the global scope fixes this. I also added a stop and start function to test the issue you mentioned in the example above.
UPDATED - I added some code to the stop interval to reset the interval to undefined. I found an example of this usage on Angular's site so it might be worth a try to see if it fixes your other issue.
var app = angular.module('app', []);
app.controller('BaseController', function($interval) {
var self = this;
var interval;
function countDown(total) {
total = total * 60;
interval = $interval(function() {
var minutes = Math.floor(total / 60);
var seconds = total - minutes * 60;
if (minutes < 1) {
minutes = '0:';
} else {
minutes = minutes + ':';
}
if (seconds < 10) {
seconds = '0' + seconds;
}
self.remainingTime = "Remaining time: " + minutes + seconds;
total--;
if (minutes === '0:' && seconds === '00') {
$interval.cancel(interval);
}
}, 1000);
}
self.stopInterval = function(){
if (angular.isDefined(interval)) {
$interval.cancel(interval);
interval = undefined;
}
}
self.startInterval = function(){
countDown(10);
}
});
Then in the html I added a button to start and stop the interval like so:
<body ng-app="app">
<div ng-controller="BaseController as baseCtrl">
{{ baseCtrl.remainingTime }}
<div>
<button ng-click="baseCtrl.startInterval()">Start Countdown</button>
<button ng-click="baseCtrl.stopInterval()">Stop Countdown</button>
</div>
</div>
</body>
You can view the codepen example here

Timer to be displayed on a webpage

I want to add a count up timer to my webpage, as in, a label that contains 0:00:00 should start displaying 0:00:01 and so on until the stop button is clicked.
Is there a simple javascript/jquery solution to this?
<html>
<head>
<title>Home</title>
<script src="jquery-1.11.1.js">
</script>
<script>
$(document).ready(function(){
$("p").click(function(){
//psst. psst.
});
});
</script>
</head>
<body>
<form>
<table>
<tr>
<td><input type="text" id="project" placeholder="project"></td>
<td><p id="timer">0:00:00<p></td>
</tr>
</table>
</form>
</body>
</html>
I tried something in Vanilla JS HERE
var seconds=0, minutes=0, hours=0;
var counter;
var stop,start;
var counting = false;
window.onload = function () {
counter = document.getElementById('counter');
stop = document.getElementById('stop');
stop.onclick = function () {
counting = false;
}
start = document.getElementById('start');
start.onclick = function() {
counting = true;
timer();
}
counting = true;
timer();
}
function timer() {
if (seconds >= 60) {
minutes++;
seconds = 0;
}
if (minutes >= 60) {
hours++;
minutes = 0;
}
counter.innerHTML = hours + ":" + minutes + ":" + seconds;
if (counting) {
seconds++;
setTimeout(timer, 1000);
}
}
If you need more info leave a comment..
time.js
function time(id)
{
date = new Date;
h = date.getHours();
if(h<10)
{
h = "0"+h;
}
m = date.getMinutes();
if(m<10)
{
m = "0"+m;
}
s = date.getSeconds();
if(s<10)
{
s = "0"+s;
}
result = h+':'+m+':'+s;
document.getElementById(id).innerHTML = result;
// "setTimeout" call function "time" every 1 second (1000 milliseconds)
setTimeout('time("'+id+'");','1000');
return true;
}
HTML
<html>
<head>
<title>Time in Javascript</title>
<script type="text/javascript" src="time.js"></script>
</head>
<body>
<span id="time"></span>
<script type="text/javascript">window.onload = time('time');</script>
</body>
</html>
Try this way
Use https://github.com/jchavannes/jquery-timer
Include this files in head
<script src="http://code.jquery.com/jquery-1.8.3.js" type="text/javascript">
<script src="http://jchavannes.com/include/scripts/3p/jquery.timer.js" type="text/javascript">
Script
var Example1 = new (function() {
var $stopwatch, // Stopwatch element on the page
incrementTime = 70, // Timer speed in milliseconds
currentTime = 0, // Current time in hundredths of a second
updateTimer = function() {
$stopwatch.html(formatTime(currentTime));
currentTime += incrementTime / 10;
},
init = function() {
$stopwatch = $('#stopwatch');
Example1.Timer = $.timer(updateTimer, incrementTime, true);
};
this.resetStopwatch = function() {
currentTime = 0;
this.Timer.stop().once();
};
$(init);
});
function formatTime(time) {
var min = parseInt(time / 6000),
sec = parseInt(time / 100) - (min * 60),
hundredths = pad(time - (sec * 100) - (min * 6000), 2);
return (min > 0 ? pad(min, 2) : "00") + ":" + pad(sec, 2) + ":" + hundredths;
}
function pad(number, length) {
var str = '' + number;
while (str.length < length) {str = '0' + str;}
return str;
}
Example1();
DEMO
By using setInterval and Date
You can use button to stop and start timer.
var d = new Date();
d.setHours(0,0,0,0);
setInterval((function(){
return function(){
d.setSeconds(d.getSeconds()+1);
var t = d.toLocaleTimeString("en-US", {hour12: false});
document.getElementById("demo").innerHTML = t;
}
})(), 1000);
Fiddle Demo
Please try this fiddle for your solution.
JS.
var hour = 0;
var min = 0;
var second = 0;
var i=setInterval(function(){
second++;
if(second > 59){
second = 0;
min++;
if(min>59){
hour++;
min = 0;
}
}
var timer_time = (hour > 9 ? hour : '0'+hour)+':'+(min > 9 ? min : '0'+min)+':'+(second > 9 ? second : '0'+second);
$('#timer').html(timer_time);
}, 1000);
$('#stop_timer').click(function(){
clearInterval(i);
});
HTML
<p id='timer'>00:00:00</p>
<button id='stop_timer'>Stop Timer</button>
Thanks
Use timing events like documented at http://www.w3schools.com/js/js_timing.asp.

Trying to code improvement for JS countdown with localStorage

I'm not enough skilled in js and jq, and think this code looks really bad:
var updateTimerApple = function() {
var timerApple = localStorage.getItem('timerApple');
if ( timerApple < 0 ) {
$(".apple").css("display", "none");
}
else if (timerApple == 0) {
$(".apple").html("Apple ok").css("display", "block");
}
else {
timerApple--;
localStorage.setItem('timerApple', timerApple);
var hours = Math.floor(timerApple / 3600);
var minute = Math.floor((timerApple - (hours * 3600)) / 60);
var second = timerApple - (hours * 3600) - (minute * 60);
if (hours < 1) hours = "0" + hours;
if (minute < 10) minute = "0" + minute;
if (second < 10) second = "0" + second;
$(".apple").html("Apple tree:"+" "+hours+"ч"+" "+minute+"м"+" "+second+"с"+" ");
$(".apple").css("display", "block");
}
};
var updateTimeroak = function() {
var timeroak = localStorage.getItem('timeroak');
if ( timeroak < 0 ) {
$(".oak").css("display", "none");
}
else if (timeroak == 0) {
$(".oak").html("Oak ok").css("display", "block");;
}
else {
timeroak--;
localStorage.setItem('timeroak', timeroak);
var hours = Math.floor(timeroak / 3600);
var minute = Math.floor((timeroak - (hours * 3600)) / 60);
var second = timeroak - (hours * 3600) - (minute * 60);
if (hours < 1) hours = "0" + hours;
if (minute < 10) minute = "0" + minute;
if (second < 10) second = "0" + second;
$(".oak").html("Oak:"+" "+hours+"ч"+" "+minute+"м"+" "+second+"с"+" ");
$(".oak").css("display", "block");
}
};
$(function() {
setInterval(updateTimerApple, 1000);
$(".startApple").click( function() {
localStorage.setItem('timerApple', 51480);
$(".apple").removeAttr('style');
});
$(".apple").click( function() {
localStorage.removeItem('timerApple');
$(".apple").css({"display": "none", "visibility": "hidden","width":"0","height":"0", "padding":"0", "margin":"0"});
});
});
$(function() {
setInterval(updateTimeroak, 1000);
$(".startoak").click( function() {
localStorage.setItem('timeroak', 176400);
$(".oak").removeAttr('style');
});
$(".oak").click( function() {
localStorage.removeItem('timeroak');
$(".oak").css({"display": "none", "visibility": "hidden","width":"0","height":"0", "padding":"0", "margin":"0"});
});
});
<body>
<div class="content">
<div class="menu">
<button class="startApple">Apple</button>
<button class="startoak">Oak</button>
</div>
<div class="item apple"></div>
<div class="item oak"></div>
</div>
</body>
Or http://jsfiddle.net/38N6x/1/
It works fine, but I am trying to improve it, making it more generic.
Looking for something like this:
function updateTimer(n,t) {
this.n=n;
this.t=localStorage.getItem('n');
if ( t < 0 ) {
$(".apple").css("display", "none");
}
else if (t == 0) {
$(".apple").html("Apple ok").css("display", "block");
}
else {
this.t--;
localStorage.setItem('n', this.t);
var hours = Math.floor(t / 3600);
var minute = Math.floor((t - (hours * 3600)) / 60);
var second = t - (hours * 3600) - (minute * 60);
if (hours < 1) hours = "0" + hours;
if (minute < 10) minute = "0" + minute;
if (second < 10) second = "0" + second;
$(".apple").html("Apple tree:"+" "+hours+"ч"+" "+minute+"м"+" "+second+"с"+" ");
$(".apple").css("display", "block");
}
};
$(function() {
setInterval(updateTimer, 1000);
$(".startApple").click( function() {
var apple = new updateTimer ("apple", 23)
$(".apple").removeAttr('style');
});
$(".apple").click( function() {
localStorage.removeItem('apple');
$(".apple").css({"display": "none", "visibility": "hidden","width":"0","height":"0", "padding":"0", "margin":"0"});
});
});
But this code not works. Browser always returns NaN for $(".apple").html("Apple tree:"+" "+hours+"ч"+" "+minute+"м"+" "+second+"с"+" ");
Thx for any help.
After spending some time, i'm found the way for code optimisation.
JS
function catDate(catID, catTime) {
var s = new Date();
s.setSeconds(s.getSeconds() + catTime);
localStorage.setItem(catID, s);
}
function CountDownTimer(dt, id) {
var end = new Date(dt);
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour * 24;
var timer;
function showRemaining() {
var now = new Date();
var distance = end - now;
if (dt == 0) {
document.getElementById(id).style.display='none';
return;
}
else if(distance < 0) {
document.getElementById(id).innerHTML = 'Сan collect';
document.getElementById(id).style.display='block';
return;
}
var days = Math.floor(distance / _day);
var hours = Math.floor((distance % _day) / _hour);
var minutes = Math.floor((distance % _hour) / _minute);
var seconds = Math.floor((distance % _minute) / _second);
document.getElementById(id).innerHTML = days + 'd ';
document.getElementById(id).innerHTML += hours + 'h ';
document.getElementById(id).innerHTML += minutes + 'm ';
document.getElementById(id).innerHTML += seconds + 's ';
document.getElementById(id).style.display='block';
}
timer = setInterval(showRemaining, 1000);
}
CountDownTimer(localStorage.getItem('apple'), 'apple');
CountDownTimer(localStorage.getItem('oak'), 'oak');
$(function() {
$(".startapple").click( function() {
catDate("apple", 5);
});
$("#apple").click( function() {
localStorage.setItem('apple', 0);
});
});
$(function() {
$(".startoak").click( function() {
catDate("oak", 2000);
});
$("#oak").click( function() {
localStorage.removeItem('oak');
});
});
$(function() {
$('div').click( function() {
location.reload();
});
});
HTML
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Farm Frenzy</title>
<link rel="stylesheet" media="screen" href="css/style.css"/>
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
<script type='text/javascript' src='js/items.js'></script>
<script type='text/javascript' src='js/itemscall.js'></script>
</head>
<body>
<div class="content">
<div class="menu">
<button class="startapple">Apple</button>
<button class="startoak">Oak</button>
</div>
<div id="apple" class="item"></div>
<div id="oak" class="item"></div>
</body>
</html>
But still have one problem: if user adding new timer (or setting localStorage.setItem('item', 0), for timer hiding), timer shows (or hiding) only after page refresh. Fixed this with
$(function() {
$('div').click( function() {
location.reload();
});
});
But i'm looking for better way.

plain count up timer in javascript

I am looking for a simple count up timer in javascript. All the scripts I find are 'all singing all dancing'. I just want a jQuery free, minimal fuss count up timer that displays in minutes and seconds. Thanks.
Check this:
var minutesLabel = document.getElementById("minutes");
var secondsLabel = document.getElementById("seconds");
var totalSeconds = 0;
setInterval(setTime, 1000);
function setTime() {
++totalSeconds;
secondsLabel.innerHTML = pad(totalSeconds % 60);
minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));
}
function pad(val) {
var valString = val + "";
if (valString.length < 2) {
return "0" + valString;
} else {
return valString;
}
}
<label id="minutes">00</label>:<label id="seconds">00</label>
Timer for jQuery - smaller, working, tested.
var sec = 0;
function pad ( val ) { return val > 9 ? val : "0" + val; }
setInterval( function(){
$("#seconds").html(pad(++sec%60));
$("#minutes").html(pad(parseInt(sec/60,10)));
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="minutes"></span>:<span id="seconds"></span>
Pure JavaScript:
var sec = 0;
function pad ( val ) { return val > 9 ? val : "0" + val; }
setInterval( function(){
document.getElementById("seconds").innerHTML=pad(++sec%60);
document.getElementById("minutes").innerHTML=pad(parseInt(sec/60,10));
}, 1000);
<span id="minutes"></span>:<span id="seconds"></span>
Update:
This answer shows how to pad.
Stopping setInterval MDN is achieved with clearInterval MDN
var timer = setInterval ( function(){...}, 1000 );
...
clearInterval ( timer );
Fiddle
The following code works as a count-up timer. It's pure JavaScript code which shows hour:minute:second. It also has a STOP button:
var timerVar = setInterval(countTimer, 1000);
var totalSeconds = 0;
function countTimer() {
++totalSeconds;
var hour = Math.floor(totalSeconds /3600);
var minute = Math.floor((totalSeconds - hour*3600)/60);
var seconds = totalSeconds - (hour*3600 + minute*60);
if(hour < 10)
hour = "0"+hour;
if(minute < 10)
minute = "0"+minute;
if(seconds < 10)
seconds = "0"+seconds;
document.getElementById("timer").innerHTML = hour + ":" + minute + ":" + seconds;
}
<div id="timer"></div>
<div id ="stop_timer" onclick="clearInterval(timerVar)">Stop time</div>
I had to create a timer for teachers grading students' work. Here's one I used which is entirely based on elapsed time since the grading begun by storing the system time at the point that the page is loaded, and then comparing it every half second to the system time at that point:
var startTime = Math.floor(Date.now() / 1000); //Get the starting time (right now) in seconds
localStorage.setItem("startTime", startTime); // Store it if I want to restart the timer on the next page
function startTimeCounter() {
var now = Math.floor(Date.now() / 1000); // get the time now
var diff = now - startTime; // diff in seconds between now and start
var m = Math.floor(diff / 60); // get minutes value (quotient of diff)
var s = Math.floor(diff % 60); // get seconds value (remainder of diff)
m = checkTime(m); // add a leading zero if it's single digit
s = checkTime(s); // add a leading zero if it's single digit
document.getElementById("idName").innerHTML = m + ":" + s; // update the element where the timer will appear
var t = setTimeout(startTimeCounter, 500); // set a timeout to update the timer
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
startTimeCounter();
This way, it really doesn't matter if the 'setTimeout' is subject to execution delays, the elapsed time is always relative the system time when it first began, and the system time at the time of update.
Extending from #Chandu, with some UI added:
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
</head>
<style>
button {
background: steelblue;
border-radius: 4px;
height: 40px;
width: 100px;
color: white;
font-size: 20px;
cursor: pointer;
border: none;
}
button:focus {
outline: 0;
}
#minutes, #seconds {
font-size: 40px;
}
.bigger {
font-size: 40px;
}
.button {
box-shadow: 0 9px #999;
}
.button:hover {background-color: hotpink}
.button:active {
background-color: hotpink;
box-shadow: 0 5px #666;
transform: translateY(4px);
}
</style>
<body align='center'>
<button onclick='set_timer()' class='button'>START</button>
<button onclick='stop_timer()' class='button'>STOP</button><br><br>
<label id="minutes">00</label><span class='bigger'>:</span><label id="seconds">00</label>
</body>
</html>
<script>
function pad(val) {
valString = val + "";
if(valString.length < 2) {
return "0" + valString;
} else {
return valString;
}
}
totalSeconds = 0;
function setTime(minutesLabel, secondsLabel) {
totalSeconds++;
secondsLabel.innerHTML = pad(totalSeconds%60);
minutesLabel.innerHTML = pad(parseInt(totalSeconds/60));
}
function set_timer() {
minutesLabel = document.getElementById("minutes");
secondsLabel = document.getElementById("seconds");
my_int = setInterval(function() { setTime(minutesLabel, secondsLabel)}, 1000);
}
function stop_timer() {
clearInterval(my_int);
}
</script>
Looks as follows:
Fiddled around with the Bakudan's code and other code in stackoverflow to get everything in one.
Update #1 : Added more options. Now Start, pause, resume, reset and restart. Mix the functions to get desired results.
Update #2 : Edited out previously used JQuery codes for pure JS and added as code snippet.
For previous Jquery based fiddle version : https://jsfiddle.net/wizajay/rro5pna3/305/
var Clock = {
totalSeconds: 0,
start: function () {
if (!this.interval) {
var self = this;
function pad(val) { return val > 9 ? val : "0" + val; }
this.interval = setInterval(function () {
self.totalSeconds += 1;
document.getElementById("min").innerHTML = pad(Math.floor(self.totalSeconds / 60 % 60));
document.getElementById("sec").innerHTML = pad(parseInt(self.totalSeconds % 60));
}, 1000);
}
},
reset: function () {
Clock.totalSeconds = null;
clearInterval(this.interval);
document.getElementById("min").innerHTML = "00";
document.getElementById("sec").innerHTML = "00";
delete this.interval;
},
pause: function () {
clearInterval(this.interval);
delete this.interval;
},
resume: function () {
this.start();
},
restart: function () {
this.reset();
Clock.start();
}
};
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(); });
document.getElementById("restartButton").addEventListener("click", function () { Clock.restart(); });
<span id="min">00</span>:<span id="sec">00</span>
<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">
<input id="restartButton" type="button" value="Restart">
#Cybernate, I was looking for the same script today thanks for your input. However I changed it just a bit for jQuery...
function clock(){
$('body').prepend('<div id="clock"><label id="minutes">00</label>:<label id="seconds">00</label></div>');
var totalSeconds = 0;
setInterval(setTime, 1000);
function setTime()
{
++totalSeconds;
$('#clock > #seconds').html(pad(totalSeconds%60));
$('#clock > #minutes').html(pad(parseInt(totalSeconds/60)));
}
function pad(val)
{
var valString = val + "";
if(valString.length < 2)
{
return "0" + valString;
}
else
{
return valString;
}
}
}
$(document).ready(function(){
clock();
});
the css part:
<style>
#clock {
padding: 10px;
position:absolute;
top: 0px;
right: 0px;
color: black;
}
</style>
Note: Always include jQuery before writing jQuery scripts
Step1: setInterval function is called every 1000ms (1s)
Stpe2: In that function. Increment the seconds
Step3: Check the Conditions
<span id="count-up">0:00</span>
<script>
var min = 0;
var second = 00;
var zeroPlaceholder = 0;
var counterId = setInterval(function(){
countUp();
}, 1000);
function countUp () {
second++;
if(second == 59){
second = 00;
min = min + 1;
}
if(second == 10){
zeroPlaceholder = '';
}else
if(second == 00){
zeroPlaceholder = 0;
}
document.getElementById("count-up").innerText = min+':'+zeroPlaceholder+second;
}
</script>
Check out these solutions:
Compute elapsed time
Just wanted to put my 2 cents in. I modified #Ajay Singh's function to handle countdown and count up Here is a snip from the jsfiddle.
var countDown = Math.floor(Date.now() / 1000)
runClock(null, function(e, r){ console.log( e.seconds );}, countDown);
var t = setInterval(function(){
runClock(function(){
console.log('done');
clearInterval(t);
},function(timeElapsed, timeRemaining){
console.log( timeElapsed.seconds );
}, countDown);
}, 100);
https://jsfiddle.net/3g5xvaxe/
Here is an React (Native) version:
import React, { Component } from 'react';
import {
View,
Text,
} from 'react-native';
export default class CountUp extends Component {
state = {
seconds: null,
}
get formatedTime() {
const { seconds } = this.state;
return [
pad(parseInt(seconds / 60)),
pad(seconds % 60),
].join(':');
}
componentWillMount() {
this.setState({ seconds: 0 });
}
componentDidMount() {
this.timer = setInterval(
() => this.setState({
seconds: ++this.state.seconds
}),
1000
);
}
componentWillUnmount() {
clearInterval(this.timer);
}
render() {
return (
<View>
<Text>{this.formatedTime}</Text>
</View>
);
}
}
function pad(num) {
return num.toString().length > 1 ? num : `0${num}`;
}
Here is one using .padStart():
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8' />
<title>timer</title>
</head>
<body>
<span id="minutes">00</span>:<span id="seconds">00</span>
<script>
const minutes = document.querySelector("#minutes")
const seconds = document.querySelector("#seconds")
let count = 0;
const renderTimer = () => {
count += 1;
minutes.innerHTML = Math.floor(count / 60).toString().padStart(2, "0");
seconds.innerHTML = (count % 60).toString().padStart(2, "0");
}
const timer = setInterval(renderTimer, 1000)
</script>
</body>
</html>
From MDN:
The padStart() method pads the current string with another string (repeated, if needed) so that the resulting string reaches the given length. The padding is applied from the start (left) of the current string.
This is how I build timerView element which does not confuse by calling function many times.
function startOTPCounter(countDownDate){
var countDownDate = '21/01/2022 16:56:26';//Change this date!!
var x = setInterval(function() {
var now = new Date().getTime();
var distance = moment(countDownDate, 'DD/MM/YYYY hh:mm:ss').toDate().getTime() - now;
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
document.getElementById("timerView").innerHTML = minutes + "min " + seconds + "sn";
if (distance < 0) {
clearInterval(x);
// document.location.reload();
document.getElementById("timerView").innerHTML = "Expired!";
}
}, 1000);
if(window.preInterval != undefined){
clearInterval(window.preInterval);
}
window.preInterval = x;
//if(sessionStorage.preInterval != undefined){
// clearInterval(sessionStorage.preInterval);
//}
//sessionStorage.preInterval = x;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<html>
<head>
</head>
<body>
<div>
<p style="color:red; font-size: 15px; text-align:center; " id='timerView'></p>
<input type="button" name="otpGonder" value="Send Again" class="buton btn btn-default " onclick="startOTPCounter()" id="otpGonder">
</div>
</body>
</html>

Categories

Resources