I have a working count down timer in java script and it count down from 120 seconds to 0, now I want to change it to becomes a COUNT UP timer, try few thing still not work. could anyone help to change it to COUNT UP instead of COUNT DOWN.
Here is the code below:
<script type="text/javascript" >
var m = 0;
var s = 120;
var timer_container = document.getElementById("survey-timer");
timer_container.innerHTML = s + "." + m;
function timer() {
if (m<=0) {
m = 9;
s -= 1;
}
if(s>=0) {
m -= 1;
timer_container.innerHTML = s + "." + m;
setTimeout(timer,100);
}
}
</script>
You want to count up from 120 or from 0.. below one just count up from 0..
<script type="text/javascript" >
var m=0
var s=0
var timer_container=document.getElementById("survey-timer");
timer_container.innerHTML=s+"."+m;
function timer(){
if (m>=9){
m=-1;
s+=1;
}
if(s>=0){
m+=1;
timer_container.innerHTML=s+"."+m;
setTimeout(timer,100);
}
}
</script>
Here is working example from jsfiddle
If it were me, I would do this:
var base = new Date();
var timer_container = document.getElementById("survey-timer");
timer();
function timer() {
var now = new Date();
// elapsed time in seconds
var elapsed = (now - base) / 1000.0;
timer_container.innerHTML = elapsed.toFixed(1);
setTimeout(timer, 100);
}
<div id="survey-timer"> </div>
Because I think the technique used in the question and in rahul's answer might 'slip' if the timeout were delayed for whatever reason.
Related
I create time using toLocaleString() and then I use this code to change the color every sec but it work only last color not for all.
var time=document.getElementById("time");
setInterval(function() {
var da=new Date();
var ti=da.toLocaleTimeString();
// console.log("yes");
time.innerHTML=ti;
}, 1000);
setInterval(function() {
var arr=["red","blue","green"];
var i=Math.floor(Math.random() * 2) + 1;
// console.log(i);
time.style.color=time.classList.add(arr[i]);
console.log(i);
}, 1000);
You can try this trick to achieve the requirement you have.
To get the colors in sequence, try this :
var time=document.getElementById("time");
var arr=["red","blue","green"];
let index = 0;
setInterval(function() {
var da = new Date();
var ti = da.toLocaleTimeString();
time.innerHTML = ti;
time.style.color = arr[index];
if (index < arr.length) { index++; } else { index = 0 }
}, 1000);
<div id="time"></div>
To get the random color from an array, try this :
var time=document.getElementById("time");
var arr=["red","blue","green"];
setInterval(function() {
var da = new Date();
var ti = da.toLocaleTimeString();
time.innerHTML = ti;
const index = Math.floor(Math.random() * arr.length);
time.style.color = arr[index];
}, 1000);
<div id="time"></div>
Please i have a JavaScript countdown timer code that i got from stackoverflow that is a solution to my countdown timer project. this existing code counts down time from 30minutes down to 1 and start over again. and it gives the same count result to every user at the same time. But my challenge with the code is that i was not able to modify it in other to be able to regulate the count duration, because i want it to countdown from 2minutes to 0 and start over again continually,but not exceeding 2minutes. Please i need someone that will copy this code and run it a see if you can regulate the duration and help me with the solution. thanks in anticipation.
The code is as follows:
setInterval(function() {
function addZero(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
var x = document.getElementById("timer");
var d = new Date();
var s = (d.getSeconds());
var m = (d.getMinutes());
var a = addZero(30 - m);
var b = addZero(60 - m);
var c = (60 - s);
var z = "<span style='color:red;font-size:50px;'>" + "Break" + "</span>";
var v = "<span style='color:black;font-size:24px;'>" + "Break" + "</span>";
if (m > 30) {
y = b;
}
else if (m < 30) {
y = a;
}
if (y < 2 && c < 15) {
q = z;
}
else {
q = v;
}
var t = y + (":" + addZero(c) + " Till Station " + (q));
x.innerHTML = t;
}, 250);
<div align="center" id="timer" style='color:black;font-size:24px;' ></div>
The code you presented deserves a few remarks:
Variable names should be descriptive, not one-letter a, b, c...
Variables should be defined explicitly, not implicitly global, like now happens for y and q
When m is 30, then y does not get a value... this cannot be right.
If that last point would be corrected, then the logic for setting z would pose a new problem.
Styling should be done as much as possible via CSS classes, not via style attribute settings.
Here is how you could do it. You can set the first two constants to your liking:
// Maximum number of seconds for the timer (e.g. 120 = 2 minutes)
const MAX_SECS = 120;
// Number of seconds below which text gets highlighted
const WARN_SECS = 15;
// DOM
const spanMinutes = document.getElementById("min");
const spanSeconds = document.getElementById("sec");
const spanWarning = document.getElementById("break");
// For formatting numbers with 2 digits
const twoDigits = i => i.toString().padStart(2, 0);
setInterval(() => {
let seconds = MAX_SECS - Math.floor(Date.now() / 1000) % MAX_SECS;
spanMinutes.textContent = twoDigits(Math.floor(seconds / 60))
spanSeconds.textContent = twoDigits(seconds % 60);
spanWarning.classList.toggle("warn", seconds < WARN_SECS);
}, 250);
#timer {
text-align: center;
font-size: 24px;
}
.warn {
color: red;
}
<div id="timer"><span id="min">00</span>:<span id="sec">00</span>
till station <span id="break">breaks down</break>
</div>
Im wondering what is wrong with this for loop here. I'm trying to make a Pomodoro Study Timer, a study technique that suggests that you break down studying into 25-minute chunks that are followed by 3-5 minute breaks. here I have 2 timers that run in sequence, one after the other. When the first timer reaches zero, the second one starts. For now, i have timers set to 5 seconds and 3 seconds respectively in order to make testing quicker. It all works fine until I put the whole thing into a for loop which then brings some unexpected behaviour. I want to loop the entire function based on user input which informs the code on how many times to loop the counters(this isnt setup yet).
The timers are started by pressing a button on an html page. The button executes the pomo() function at the bottom, which contains a loop that should loop the start() function.
PS, I'm a total ultra noob so apologies if this is just terrible code, I'm really new to this :)
var time25 = 5;
var time5 = 3;
var timeElapsed25 = 0;
var timeElapsed5 = 0; // initializes time elapsed to zero
var time = document.getElementsByClassName("header"); //links to html
time[0].innerHTML = time25; // sets output to html
function convertToMin(s) {
mins = Math.floor(s / 60);
let minsStr = mins.toString();
if (minsStr.length === 1) {
mins = '0' + mins;
}
sec = s % 60;
let secStr = sec.toString();
if (secStr.length === 1) {
sec = '0' + sec;
}
return mins + ':' + sec;
}
function start() {
var timer25 = setInterval(counter25, 1000);
console.log("timer1");
function counter25() {
timeElapsed25++
time[0].innerHTML = convertToMin(time25 - timeElapsed25);
if (timeElapsed25 === time25) {
console.log("timer2")
clearInterval(timer25);
timeElapsed25 = 0;
var timer5 = setInterval(counter5, 1000);
function counter5() { //Counter For 5 minute break
timeElapsed5++;
time[0].innerHTML = convertToMin(time5 - timeElapsed5);
if (timeElapsed5 === time5) {
clearInterval(timer5);
timeElapsed5 = 0;
}
}
}
}
}
function pomo() {
for (j = 0; j < 3; j++) {
start();
}
}
You shouldn't call start() in a loop. setInterval() doesn't wait for the the countdown to complete, it returns immediately, so you're starting all 3 timers at the same time.
What you should do is call start() again when both timers complete. To put a limit on the number of repetitions, use a count parameter, and decrement it each time you call again.
var time25 = 5;
var time5 = 3;
var timeElapsed25 = 0;
var timeElapsed5 = 0; // initializes time elapsed to zero
var time = document.getElementsByClassName("header"); //links to html
time[0].innerHTML = time25; // sets output to html
function pomo() {
start(3);
}
function start(count) {
if (count == 0) { // reached the limit
return;
}
var timer25 = setInterval(counter25, 1000);
console.log("timer1");
function counter25() {
timeElapsed25++
time[0].innerHTML = convertToMin(time25 - timeElapsed25);
if (timeElapsed25 === time25) {
console.log("timer2")
clearInterval(timer25);
timeElapsed25 = 0;
var timer5 = setInterval(counter5, 1000);
function counter5() { //Counter For 5 minute break
timeElapsed5++;
time[0].innerHTML = convertToMin(time5 - timeElapsed5);
if (timeElapsed5 === time5) {
clearInterval(timer5);
timeElapsed5 = 0;
start(count - 1); // Start the next full iteration
}
}
}
}
}
function convertToMin(s) {
mins = Math.floor(s / 60);
let minsStr = mins.toString();
if (minsStr.length === 1) {
mins = '0' + mins;
}
sec = s % 60;
let secStr = sec.toString();
if (secStr.length === 1) {
sec = '0' + sec;
}
return mins + ':' + sec;
}
I want to run x function for n seconds. What I tried:
var stop = false;
setTimeout(function(){stop = true}, n);
while(!stop) x();
but this didn't work... As I understood the reason is that setTimeout waiting until no task is running and then executes the function. Is that right?
Another way to do this is like this:
var stop = false, started = Date.now();
while(!stop) {
if((Date.now() - started) > n) stop = true;
else x();
}
Is there any other better way?
var stop = false;
setTimeout(function(){stop = true}, n);
var interval = setInterval(function(){
if(!stop){x();}else{clearInterval(interval);}
}, 0);
the while statement will block the timeout function, if you don't mind using setInterval, you can do it like this.
i will do like this
var t = new Date().getSeconds() + 10; // 10 seconds
while(new Date().getSeconds() <= t)
{
//loop
}
You can schedule it repeatedly while time's not up:
var runRepeatedly = function(f, secs) {
var start = Date.now();
var reschedule = function() {
var now = Date.now();
if (now - start < secs * 1000) {
setTimeout(repeat, 0)
}
}
var repeat = function() {
f();
reschedule();
};
repeat();
}
...
runRepeatedly(x, n);
Note that x should not take too long to return.
Here my solution:
<html>
<body>
<p id="demo"></p>
<button onclick="clearInterval(myVar)">Stop time</button>
<script>
var myVar = setInterval(function(){myTimer()},1000);
function myTimer() {
var d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
</script>
</body>
</html>
I have been searching the entire day for a solution to this problem. I like this Counter I found on StackOverflow, but because I am inexperienced using JavaScript, I am not entirely sure how to stop it.
I figured out how to set the value and when to start counting etc, but now I want to add a maximum value. IE: If the counter reaches 20 million, then stop.
I tried the following, but it doesn't work:
var simplicity = formatMoney(20000000);
if (amount.innerText <= simplicity){
function update() {
var current = (new Date().getTime() - start)/1000*0.36+0;
amount.innerText = formatMoney(current);
}
setInterval(update,1000);
}
else{
amount.innerText = simplicity;
}
Try this
var max = 20000000;
var intervalId = setInterval(function () {
var current = (new Date().getTime() - start)/1000*0.36+0;
if (current > max) {
amount.innerText = formatMoney(max);
clearInterval(intervalId);
} else {
amount.innerText = formatMoney(current);
}
}, 1000);
Use clearInterval(id) to stop intervals.