Progress bar with duration and percentage - javascript

I want to create a progress bar that has a duration ( the time that it takes to finish the animation) and a percentage.
So I want this progress bar to take 3000ms to finish ( to get to 100%):
So far :
<div id="box"></div>
<script>
function start(){
var duration = 5000; // it should finish in 5 seconds !
var max = 100;
var i = 0 ;
var interval = setInterval(function(){
i++;
offset = (max*i)/duration;
console.log(offset);
$("#box").css("width", offset + "px");
$("#box").text(parseInt(offset) + "%");
if(i>=duration){
alert("done "+i);
clearInterval(interval);
}
}, 1);
}
</script>
It works but it takes way longer that 5000ms .
I've also added Jquery tag because I don't care if I do this with javascript or jquery
Thanks guys.

Feel free to tweak the below as needed, but the main problems are fixed. Namely, your interval shouldn't be running every 1 millisecond, and it should complete at 100%. The below will set your interval to always run at each 1%.
function start(){
var duration = 5000; // it should finish in 5 seconds !
var percent = duration / 100; // 1 percent of duration
var i = 0 ;
var interval = setInterval(function(){
i++;
$("#box").css("width", i + "px");
$("#box").text(i + "%");
if(i>=100){
alert("done");
clearInterval(interval);
}
}, percent);
}

The simplest solution could be is ot use jQuery's .animate()
function start() {
var duration = 5000; // it should finish in 5 seconds !
$("#box").stop().css("width", 0).animate({
width: 100
}, {
duration: duration,
progress: function(promise, progress, ms) {
$(this).text(Math.round(progress * 100) + '%');
}
});
}
start()
#box {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="box"></div>
another solution will be is to look at the time difference
function start() {
var duration = 5000; // it should finish in 5 seconds !
var st = new Date().getTime();
var interval = setInterval(function() {
var diff = Math.round(new Date().getTime() - st),
val = Math.round(diff / duration * 100);
val = val > 100 ? 100 : val;
$("#box").css("width", val + "px");
$("#box").text(val + "%");
if (diff >= duration) {
clearInterval(interval);
}
}, 100);
}
start()
#box {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="box"></div>
Same using requestAnimationFrame
function start() {
var duration = 5000; // it should finish in 5 seconds !
var st = window.performance.now();
window.requestAnimationFrame(function step(time) {
var diff = Math.round(time - st),
val = Math.round(diff / duration * 100);
val = val > 100 ? 100 : val;
$("#box").css("width", val + "px");
$("#box").text(val + "%");
if (diff < duration) {
window.requestAnimationFrame(step);
}
})
}
start()
#box {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="box"></div>

Not sure if you're using it yet, but you could bootstrap to do this.
<div class="progress-bar" style="width: 0;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" >
var value = 0;
function start(){
value += 5;
$( ".progress-bar" ).css("width", value+"%").attr("aria-valuenow", value);
if ( value%5 == 0 ) {
return setTimeout(restart, 100);
}
if(value >= 100)
return;
else
setTimeout(restart, 50);
}
function restart() {
start();
}

I used the answer provided by some of you but you got one thing wrong on the progress bar. You need to change the "px" in jquery to be "%" otherwise the progress bar will only be 100px wide. Since I am using the Bootstrap Progress bar the values here amend to what is already there and fill up the progress wrapper as the page loads.
function start() {
var duration = 5000; // it should finish in 5 seconds !
var st = window.performance.now();
window.requestAnimationFrame(function step(time) {
var diff = Math.round(time - st),
val = Math.round(diff / duration * 100);
val = val > 100 ? 100 : val;
$(".progress-bar").css("width", val + "%");
$(".progress-bar").text(val + "%");
if (diff < duration) {
window.requestAnimationFrame(step);
}
})
}
start()

Related

How to Stop Interval After on Full Run

Can you please take a look at this demo and let me know how I can stop the animation and interval after reaching 100% and filling the progress bar
I tried adding clearInterval(myVar); to the end of interval but this stops incrementting the percentage text
$(".progress-bar").animate({
width: "100%"
}, 3000);
var myVar=setInterval(function(){myTimer()},1);
var count = 0;
function myTimer() {
if(count < 100){
$('.progress').css('width', count + "%");
count += 0.05;
document.getElementById("demo").innerHTML = Math.round(count) +"%";
// code to do when loading
}
else if(count > 99){
// code to do after loading
count = 0;
}
}
clearInterval(myVar);
Don't use a timer for this. jQuery provides a way for you to listen to the progress of the animation:
$(".progress-bar").animate({
width: "100%"
},{
duration: 3000,
progress: function(_, progr) {
$('#demo').text( Math.round(100 * progr));
}
});
See your updated fiddle
NB: I changed your demo element to a span, as a p will break the % to the next line.
You need to put the code of clearing the interval in the block where you handle the finishing of loading.
var myVar = setInterval(function() {
myTimer()
}, 1);
var count = 0;
function myTimer() {
if (count < 100) {
$('.progress').css('width', count + "%");
count += 0.05;
document.getElementById("demo").innerHTML = Math.round(count) + "%";
// code to do when loading
} else if (count > 99) {
// code to do after loading
count = 0;
// loading is done, clear the interval
clearInterval(myVar);
}
}

Javascript Loading Bars according time

I've searched so much but I can't figure it out how to configure my bars.
I plan to put 3 loading bars that execute automatically according time:
1st will start from 30 to 60 seconds
2nd from 300 to 1800 seconds
3rd from 1801 to 1860 seconds
My Code is this ( be aware that I don't know how to change this values, I tried but don't work properly... This is the help I need, the frame stuff )
var my1Bar = setTimeout(start1Bar, 30000);
var my2Bar = setTimeout(start2Bar, 300000);
var my3Bar = setTimeout(start3Bar, 1800000);
function start1Bar() {
var elem = document.getElementById("my1Bar");
var width = 10;
var id = setInterval(frame, 10);
function frame() {
if (width >= 100) {
clearInterval(id);
} else {
width++;
elem.style.width = width + '%';
}
}
}
function start2Bar() {
var elem = document.getElementById("my2Bar");
var width = 10;
var id = setInterval(frame, 10);
function frame() {
if (width >= 100) {
clearInterval(id);
} else {
width++;
elem.style.width = width + '%';
}
}
}
function start3Bar() {
var elem = document.getElementById("my3Bar");
var width = 10;
var id = setInterval(frame, 10);
function frame() {
if (width >= 100) {
clearInterval(id);
} else {
width++;
elem.style.width = width + '%';
}
}
}
Thank you all
startBar(3000,4000 ,"my1Bar");
startBar(4001,20000 ,"my2Bar");
startBar(20001,22000,"my3Bar");
function startBar(start_ms,end_ms,id){
return setTimeout(function(){
loadBar(start_ms,end_ms,id);
}, start_ms);
}
function loadBar(start_ms,end_ms,id){
var elem = document.getElementById(id);
var widthAtStart = 0;
var widthAtEnd = 100;
var timeDuration=end_ms-start_ms;
var remindWidth=widthAtEnd-widthAtStart;
var curWidth=widthAtStart;
var lastTime=Date.now();
var intervalId = setInterval(frame, 10);
function frame() {
var dt=Date.now()-lastTime;
lastTime=Date.now();
var w=remindWidth*dt/timeDuration;
if (curWidth >= widthAtEnd) {
clearInterval(intervalId);
elem.style.width = '100%';
} else {
curWidth+=w;
elem.style.width = curWidth + '%';
}
}
}
.bars>div{
position:relative;
width:100%;
height:22px;
padding:1px;
margin:2px;
background:#ccc;
}
.bars>div>div{
position:absolute;
height:20px;
width:0;
background:red
}
<div class="bars">
<div><div id="my1Bar"></div></div>
<div><div id="my2Bar"></div></div>
<div><div id="my3Bar"></div></div>
</div>
Here is a bit refactored version of your code. To run a progress bar you need to call startBar() function with the time you want it to start and end and the id of a progress bar element. For example, in the code below the first bar will start after 1 second and end after 6 seconds (running for 5 seconds in total).
I also used HTML5 progress element. It is much better than using divs as progress is semantic and you don't have to manipulate any css parameters, you just change it's value. Plus it has a bonus of looking native to the platform and browser it is rendered on. However, if you want to style it to look the same on all platforms, it can be a bit of a pain. Here is a styling guide for progress element
startBar(1, 6, "first");
startBar(3, 6, "second");
startBar(5, 8, "third");
function startBar(from, to, id) {
// Convert seconds to miliseconds
from *= 1000;
to *= 1000;
// Delay the start of the loop for 'from' seconds
setTimeout(function() {
var bar = document.getElementById(id);
var duration = to - from;
var start = Date.now();
// Start the loop
var loop = setInterval(function() {
var runningFor = Date.now() - start;
if (runningFor <= duration) {
bar.value = Math.ceil(runningFor / duration * 100);
} else {
bar.value = 100;
clearInterval(loop);
}
}, 10);
}, from);
}
progress {
width: 100%;
}
<progress id="first" value="0" max="100"></progress>
<progress id="second" value="0" max="100"></progress>
<progress id="third" value="0" max="100"></progress>

how to place a time display box in a time progress bar

i have time progress bar. i use this code.i need time runner inside blue box.
how can i fix it, means when the yellow bar move depends on time need a time
display box.
var timer = 0,
perc = 0,
timeTotal = 2500,
timeCount = 1,
cFlag;
function updateProgress(percentage) {
var x = (percentage/timeTotal)*100,
y = x.toFixed(3);
$('#pbar_innerdiv').css("width", x + "%");
$('#pbar_innertext').text(y + "%");
}
function animateUpdate() {
if(perc < timeTotal) {
perc++;
updateProgress(perc);
timer = setTimeout(animateUpdate, timeCount);
}
}
$(document).ready(function() {
$('#pbar_outerdiv').click(function() {
if (cFlag == undefined) {
clearTimeout(timer);
perc = 0;
cFlag = true;
animateUpdate();
}
else if (!cFlag) {
cFlag = true;
animateUpdate();
}
else {
clearTimeout(timer);
cFlag = false;
}
});
});
#pbar_outerdiv { cursor: pointer; }
You already have the actual time in the updateProgress() method, so its as simple as changing the line setting the percentage to this:
$('#pbar_innertext').text((percentage / 100).toFixed(2) + " s");
JSFiddle: https://jsfiddle.net/McNetic/hnfRe/395/
Edit: With different browser, I now see the next problem: The animation can take much longer than the advertised time of 2500 ms (because of the very high update frequency of 1000 frames per second). So you should do less animation frames and calculate the percentage base on actual time measuring, like this:
https://jsfiddle.net/McNetic/hnfRe/396/
Check this JSFiddle. You can adjust the CSS: colours, sizes, etc to your needs.
Basically I put the text outside the #pbar_innerdiv in a span box.
<div id="pbar_outerdiv">
<div id="pbar_innerdiv"></div>
<span id="pbar_innertext">Click!</span>
</div>
Edit
So I edited the script and I hope now it matches your needs: JSFiddle Link. This is the script I used:
var timer = 0,
perc = 0,
percIncreaser,
timeTotal = 2500, //Only change this value time according to your need
timeCount = 1,
secondsCount=0,
cFlag;
function updateProgress(percentage,time) {
//var x = (percentage/timeTotal)*100;
$('#pbar_innerdiv').css("width", percentage + "%");
$('#pbar_innertext').text(time/1000 + "s");
}
function animateUpdate() {
if(perc < timeTotal) {
perc+=percIncreaser;
secondsCount+=10;
updateProgress(perc,secondsCount);
if(perc>=100) clearTimeout(timer);
else timer = setTimeout(animateUpdate, timeCount);
}
}
$(document).ready(function() {
$('#pbar_outerdiv').click(function() {
percIncreaser = 100/timeTotal*10;
if (cFlag == undefined) {
clearTimeout(timer);
perc = 0;
cFlag = true;
animateUpdate();
}
else if (!cFlag) {
cFlag = true;
animateUpdate();
}
else {
clearTimeout(timer);
cFlag = false;
}
});
});

jQuery progress timer bar

I have a progress timer bar in jQuery - here is an example http://jsfiddle.net/6h74c/
If I have time values in milliseconds, (600000 = 10 minutes, 300000 = 5 minutes, etc), how can I make the bar increment for that period of time?
In the jsfiddle link, I'm trying to set the progress bar to increase for 835000ms.
However, the setTimeout() determines how often the bar will increase and it is also basing it off of width percentage, which doesn't seem accurate - should I be doing this differently?
function updateProgress(percentage) {
$('#pbar_innerdiv').css("width", percentage + "%"); // probably not ideal
$('#pbar_innertext').text(percentage + "%");
}
function animateUpdate() {
perc++;
updateProgress(perc);
if(perc < 835000) {
timer = setTimeout(animateUpdate, 50); // probably not ideal either?
}
}
Fiddle Example
I would do something like:
var start = new Date();
var maxTime = 835000;
var timeoutVal = Math.floor(maxTime/100);
animateUpdate();
function updateProgress(percentage) {
$('#pbar_innerdiv').css("width", percentage + "%");
$('#pbar_innertext').text(percentage + "%");
}
function animateUpdate() {
var now = new Date();
var timeDiff = now.getTime() - start.getTime();
var perc = Math.round((timeDiff/maxTime)*100);
if (perc <= 100) {
updateProgress(perc);
setTimeout(animateUpdate, timeoutVal);
}
}
Simply do some good old fashioned math. It doesnt seem right because you're giving width percentage as the value of the "tick" which will eventually be 835000! Meaning you eventually have a width of "835000%"!!!
Example
var timer = 0,
perc = 0,
timeTotal = 835000,
timeCount = 50;
function updateProgress(percentage) {
var x = (percentage/timeTotal)*100,
y = x.toFixed(3);
$('#pbar_innerdiv').css("width", x + "%");
$('#pbar_innertext').text(y + "%");
}
function animateUpdate() {
if(perc < timeTotal) {
perc++;
updateProgress(perc);
timer = setTimeout(animateUpdate, timeCount);
}
}
$(document).ready(function() {
$('#pbar_outerdiv').click(function() {
clearTimeout(timer);
perc = 0;
animateUpdate();
});
});
jsFiddle Demo
Description
This just simply increases the progress every 10ms...since you know the time it takes, take that time and divide by 100 then make that your timeinterval in var timer = setInterval(updateProgressbar, 10);
HTML
<div id="progressbar"></div>
JS
var progress = 0;
var timer = setInterval(updateProgressbar, 10);
function updateProgressbar(){
$("#progressbar").progressbar({
value: ++progress
});
if(progress == 100)
clearInterval(timer);
}
$(function () {
$("#progressbar").progressbar({
value: progress
});
});
JS Fiddle Just for you
JS
var progress = 0;
var timer = setInterval(updateProgressbar, 8350);
function updateProgressbar(){
$("#progressbar").progressbar({
value: ++progress
});
if(progress == 100)
clearInterval(timer);
}
$(function () {
$("#progressbar").progressbar({
value: progress
});
});
You probably want something like this:
var currentTime = new Date().getTime();
perc = (currentTime - StarTime)/duration;
If set StartTime like that too you can calculate the percentage on every update.

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