JavaScript countdown with css circles - javascript

I have a countdown I am trying to have a visual display with css circles of the count down. But I cant figure out what to do to take away one circle at a time. My code duplicates the number of circles each loop. I know why, but what can I now do to get it to take one away each time?
JS Fiddle: http://jsfiddle.net/L0o9jmw9/
JS:
var sec = 5
function setClock() {
var totalSec = sec--;
var s = parseInt(totalSec % 60, 10);
var result = s + " seconds to go!";
document.getElementById('timeRemaining').innerHTML = result;
if(totalSec === 0){
document.getElementById('timeRemaining').innerHTML = 'time out';
}else{
for(var i = 0; i < s; i++){
//console.log(i);
$('.cont-s').prepend('<div class="cir-s"></div>');
}
setTimeout(setClock, 1000);
}
}
setClock();
HTML:
<div id="timeRemaining"></div>
<div class="cont-s"></div>
CSS:
.cir-s{
width: 20px;
height: 20px;
background: #802A2A;
-moz-border-radius: 50px;
-webkit-border-radius: 50px;
border-radius: 50px;
float:left;
}

Simply empty the HTML before each iteration:
function setClock() {
$('.cont-s').empty(); // empty the circles div
var totalSec = sec--;
var s = parseInt(totalSec % 60, 10);
var result = s + " seconds to go!";
document.getElementById('timeRemaining').innerHTML = result;
if(totalSec === 0){
document.getElementById('timeRemaining').innerHTML = 'time out';
} else {
for(var i = 0; i < s; i++){
$('.cont-s').prepend('<div class="cir-s"></div>');
}
setTimeout(setClock, 1000);
}
}

Related

Timer function not working correctly when stopped and started multiple times

First of all, you can find an example of my code in JS Fiddle and also below the question.
I'm working on a personal training webapp and basically you can hit play and then you get five minutes to do a series of tasks in a random order. The program creates the sessionTasks array in which are put in a random order tasks for the tasks array in order to fit the five minute limit. Right now the tasks array is just one I created with four tasks and the respective times just for testing.
The problem I ran into is the following: When you click the task so you can move forward to the next task, the next time you play seconds will move faster. The way I found to replicate is:
Click play.
Power through the tasks by clicking the task text very quickly.
Click play again.
Now the seconds should be moving quicker. If not, repeat what you just did. It is irregular but it usually does it in the second try.
I cannot for the life of me understand why it behaves like this. I thought that maybe it was creating more Timers that all used #taskTimer to run but that didn't make sense to me. Is it something wrong with the Timer function? What is wrong in my code?
mainMenu();
var totalSessionTasks, taskIterator, selectedTimeInSecs = 300;
var taskTimer = new Timer("#taskTimer", nextTask);
var globalTimer = new Timer("#globalTimer", function() {
});
var tasks = [
["First task", 0, 30],
["Second task", 0, 15],
["Third task", 0, 10],
["Fourth task", 3, 0]
];
var sessionTasks = [
]
function setUpSession() {
sessionTasks = []
if (tasks.length != 0) {
var sessionTasksSeconds = 0; //the seconds of the session being filled
var sessionTasksSecondsToFill = selectedTimeInSecs; //seconds left in the session to fill
var newTaskSeconds = 0; //seconds of the next task being added to the session
var sessionFull = false;
console.log('Session Empty');
while (sessionFull === false) {
var areThereAnyTaskThatFitInTheSession =
tasks.some(function(item) {
return ((item[1] * 60 + item[2]) <= sessionTasksSecondsToFill) && (item != sessionTasks[sessionTasks.length - 1]);
});
console.log(areThereAnyTaskThatFitInTheSession);
if (areThereAnyTaskThatFitInTheSession) {
do {
var randTaskNum = Math.floor(Math.random() * tasks.length);
} while (((tasks[randTaskNum][1] * 60 + tasks[randTaskNum][2]) > sessionTasksSecondsToFill) || (tasks[randTaskNum] == sessionTasks[sessionTasks.length - 1]))
sessionTasks.push(tasks[randTaskNum]);
newTaskSeconds = (tasks[randTaskNum][1]) * 60 + tasks[randTaskNum][2];
sessionTasksSecondsToFill -= newTaskSeconds;
sessionTasksSeconds += newTaskSeconds;
console.log(tasks[randTaskNum][0] + ": " + newTaskSeconds + "s");
console.log(sessionTasksSeconds)
} else if (sessionTasks.length == 0) {
note("All your tasks are too big for a game of " + selectedTimeInSecs / 60 + " minutes!");
break;
} else {
console.log('Session full');
sessionFull = true;
taskIterator = -1;
totalSessionTasks = sessionTasks.length;
console.log(totalSessionTasks);
globalTimer.set(0, sessionTasksSeconds);
nextTask();
globalTimer.run();
taskTimer.run();
}
}
} else {
note("You don't have have any tasks in your playlists!");
}
}
function nextTask() {
if (taskIterator + 1 < totalSessionTasks) {
taskIterator++;
$("#taskText").text(sessionTasks[taskIterator][0]);
globalTimer.subtract(0, taskTimer.getTotalTimeInSeconds())
taskTimer.set(sessionTasks[taskIterator][1], sessionTasks[taskIterator][2]);
$("#taskCounter").text(taskIterator + 1 + " of " + totalSessionTasks + " tasks");
} else {
mainMenu();
taskTimer.stop();
globalTimer.stop();
note("Thanks for playing!");
}
}
//timer object function
function Timer(element, callback) {
var ac, minutes, seconds, finalTimeInSeconds, displayMinutes, displaySeconds, interval = 1000,
self = this,
timeLeftToNextSecond = 1000;
this.running = false;
this.set = function(inputMinutes, inputSeconds) {
finalTimeInSeconds = inputMinutes * 60 + inputSeconds;
minutes = (Math.floor(finalTimeInSeconds / 60));
seconds = finalTimeInSeconds % 60;
this.print();
}
this.add = function(inputMinutes, inputSeconds) {
finalTimeInSeconds += inputMinutes * 60 + inputSeconds;
finalTimeInSeconds = (finalTimeInSeconds < 0) ? 0 : finalTimeInSeconds;
minutes = (Math.floor(finalTimeInSeconds / 60));
seconds = finalTimeInSeconds % 60;
this.print();
}
this.subtract = function(inputMinutes, inputSeconds) {
finalTimeInSeconds -= inputMinutes * 60 + inputSeconds;
if (finalTimeInSeconds <= 0) {
callback()
}
finalTimeInSeconds = (finalTimeInSeconds < 0) ? 0 : finalTimeInSeconds;
minutes = (Math.floor(finalTimeInSeconds / 60));
seconds = finalTimeInSeconds % 60;
this.print();
}
this.reset = function() {
this.set(0, 0);
}
this.print = function() {
displayMinutes = (minutes.toString().length == 1) ? "0" + minutes : minutes; //ternary operator: adds a zero to the beggining
displaySeconds = (seconds.toString().length == 1) ? "0" + seconds : seconds; //of the number if it has only one caracter.
$(element).text(displayMinutes + ":" + displaySeconds);
}
this.run = function() {
if (this.running == false) {
this.running = true;
var _f = function() {
secondStarted = new Date;
self.subtract(0, 1);
interval = 1000;
}
ac = setInterval(_f, interval);
}
}
this.stop = function() {
if (this.running == true) {
this.running = false;
console.log(this + "(" + element + ") was stopped");
stopped = new Date;
interval = 1000 - (stopped - secondStarted);
clearInterval(ac);
}
}
this.getTotalTimeInSeconds = function() {
return finalTimeInSeconds;
}
this.reset();
}
function note(string) {
alert(string);
}
function mainMenu() {
//EMPTY BODY
$("body").empty();
$("body").append(
//BUTTONS
"<div id='playButton' class='mainButton'><div class='buttonText mainButtonText'>PLAY</div></div>"
);
//BINDS
$("#playButton").bind("click", function(){
playMain();
setUpSession();
});
}
function playMain() {
//EMPTY BODY
$("body").empty();
$("body").append(
//TASK TEXT
"<p class='text' id='taskText'>Lorem ipsum dolor sit amet.</p>",
//TIMERS
"<div id='taskTimerWrap'><p class='text timer' id='taskTimer'>00:00</p><p class='text' id='taskTimerText'>Task Time</p></div>",
"<div id='globalTimerWrap'><p class='text timer' id='globalTimer'>00:00</p><p class='text' id='globalTimerText'>Global Time</p></div>",
//TASK COUNTER
"<div class='text' id='taskCounter'>0/0 tasks completed</div>"
);
//BINDS
$("#taskText").bind("click", nextTask);
}
#taskText {
text-align: center;
display: table;
vertical-align: middle;
height: auto;
width: 100%;
top: 50px;
bottom: 0;
left: 0;
right: 0;
position: absolute;
margin: auto;
font-size: 65px;
cursor: pointer;
}
#taskTimerWrap {
text-align: center;
top: 0;
right: 0;
left: 170px;
margin: 5px;
position: absolute;
-webkit-transition: all 0.5s ease;
}
.timer {
font-size: 64px;
margin: 0;
line-height: 0.88;
}
#taskTimerText {
font-size: 34.4px;
margin: 0;
line-height: 0.65;
}
#globalTimerWrap {
text-align: center;
top: 0;
left: 0;
right: 170px;
margin: 5px;
position: absolute;
}
#globalTimerText {
font-size: 28.5px;
margin: 0;
line-height: 0.78;
transform: scale(1, 1.2);
}
#taskCounter {
text-align: center;
bottom: 0;
right: 0;
left: 0;
width: auto;
position: absolute;
font-size: 30px;
color: #98D8D9;
-webkit-transition: all 0.5s ease;
}
#taskCounter:hover {
color: #F1F2F0
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
In Timer.stop() you change the interval that's used for the next run. Changing the interval variable in _f() isn't going to change the interval used by setInterval().
In this case you will have to use setTimeout() instead:
function Timer(element, callback) {
var ac, minutes, seconds, finalTimeInSeconds, displayMinutes, displaySeconds, timeout = 1000,
self = this,
timeLeftToNextSecond = 1000;
this.running = false;
/* ... */
this.run = function() {
if (this.running == false) {
this.running = true;
var _f = function() {
secondStarted = new Date;
self.subtract(0, 1);
ac = setTimeout(_f, 1000);
}
ac = setTimeout(_f, timeout);
}
}
this.stop = function() {
if (this.running == true) {
this.running = false;
console.log(this + "(" + element + ") was stopped");
stopped = new Date;
timeout = 1000 - (stopped - secondStarted);
clearTimeout(ac);
}
}
/* ... */
}
As I see, you are trying to set the value for variable interval from inside the interval callback function.
var _f = function() {
secondStarted = new Date;
self.subtract(0, 1);
//interval = 1000; REMOVE THIS LINE
}
interval = 1000; //ADD IT HERE
ac = setInterval(_f, interval);
Actually when setInterval is executed, the value for interval is not 1000. It's not updated by _f yet, because that function will run after the setInterval() is executed. And once setInterval() is called with the existing value of interval, changing it later has no impact on the created interval, because the setInterval() function has already set the delay time for the interval created. And the value for interval changes from it's initial value 1000 because of this line :
interval = 1000 - (stopped - secondStarted); //I'm not sure what you are trying to do with this, possibly removing this line will also fix your problem.)
Complete Working Demo:
And here is the JS Fiddle.
mainMenu();
var totalSessionTasks, taskIterator, selectedTimeInSecs = 300;
var taskTimer = new Timer("#taskTimer", nextTask);
var globalTimer = new Timer("#globalTimer", function() {
});
var tasks = [
["First task", 0, 30],
["Second task", 0, 15],
["Third task", 0, 10],
["Fourth task", 3, 0]
];
var sessionTasks = [
]
function setUpSession() {
sessionTasks = []
if (tasks.length != 0) {
var sessionTasksSeconds = 0; //the seconds of the session being filled
var sessionTasksSecondsToFill = selectedTimeInSecs; //seconds left in the session to fill
var newTaskSeconds = 0; //seconds of the next task being added to the session
var sessionFull = false;
console.log('Session Empty');
while (sessionFull === false) {
var areThereAnyTaskThatFitInTheSession =
tasks.some(function(item) {
return ((item[1] * 60 + item[2]) <= sessionTasksSecondsToFill) && (item != sessionTasks[sessionTasks.length - 1]);
});
console.log(areThereAnyTaskThatFitInTheSession);
if (areThereAnyTaskThatFitInTheSession) {
do {
var randTaskNum = Math.floor(Math.random() * tasks.length);
} while (((tasks[randTaskNum][1] * 60 + tasks[randTaskNum][2]) > sessionTasksSecondsToFill) || (tasks[randTaskNum] == sessionTasks[sessionTasks.length - 1]))
sessionTasks.push(tasks[randTaskNum]);
newTaskSeconds = (tasks[randTaskNum][1]) * 60 + tasks[randTaskNum][2];
sessionTasksSecondsToFill -= newTaskSeconds;
sessionTasksSeconds += newTaskSeconds;
console.log(tasks[randTaskNum][0] + ": " + newTaskSeconds + "s");
console.log(sessionTasksSeconds)
} else if (sessionTasks.length == 0) {
note("All your tasks are too big for a game of " + selectedTimeInSecs / 60 + " minutes!");
break;
} else {
console.log('Session full');
sessionFull = true;
taskIterator = -1;
totalSessionTasks = sessionTasks.length;
console.log(totalSessionTasks);
globalTimer.set(0, sessionTasksSeconds);
nextTask();
globalTimer.run();
taskTimer.run();
}
}
} else {
note("You don't have have any tasks in your playlists!");
}
}
function nextTask() {
if (taskIterator + 1 < totalSessionTasks) {
taskIterator++;
$("#taskText").text(sessionTasks[taskIterator][0]);
globalTimer.subtract(0, taskTimer.getTotalTimeInSeconds())
taskTimer.set(sessionTasks[taskIterator][1], sessionTasks[taskIterator][2]);
$("#taskCounter").text(taskIterator + 1 + " of " + totalSessionTasks + " tasks");
} else {
mainMenu();
taskTimer.stop();
globalTimer.stop();
note("Thanks for playing!");
}
}
//timer object function
function Timer(element, callback) {
var ac, minutes, seconds, finalTimeInSeconds, displayMinutes, displaySeconds, interval = 1000,
self = this,
timeLeftToNextSecond = 1000;
this.running = false;
this.set = function(inputMinutes, inputSeconds) {
finalTimeInSeconds = inputMinutes * 60 + inputSeconds;
minutes = (Math.floor(finalTimeInSeconds / 60));
seconds = finalTimeInSeconds % 60;
this.print();
}
this.add = function(inputMinutes, inputSeconds) {
finalTimeInSeconds += inputMinutes * 60 + inputSeconds;
finalTimeInSeconds = (finalTimeInSeconds < 0) ? 0 : finalTimeInSeconds;
minutes = (Math.floor(finalTimeInSeconds / 60));
seconds = finalTimeInSeconds % 60;
this.print();
}
this.subtract = function(inputMinutes, inputSeconds) {
finalTimeInSeconds -= inputMinutes * 60 + inputSeconds;
if (finalTimeInSeconds <= 0) {
callback()
}
finalTimeInSeconds = (finalTimeInSeconds < 0) ? 0 : finalTimeInSeconds;
minutes = (Math.floor(finalTimeInSeconds / 60));
seconds = finalTimeInSeconds % 60;
this.print();
}
this.reset = function() {
this.set(0, 0);
}
this.print = function() {
displayMinutes = (minutes.toString().length == 1) ? "0" + minutes : minutes; //ternary operator: adds a zero to the beggining
displaySeconds = (seconds.toString().length == 1) ? "0" + seconds : seconds; //of the number if it has only one caracter.
$(element).text(displayMinutes + ":" + displaySeconds);
}
this.run = function() {
if (this.running == false) {
this.running = true;
var _f = function() {
secondStarted = new Date;
self.subtract(0, 1);
//interval = 1000; REMOVE THIS LINE
}
interval = 1000; //ADD IT HERE
ac = setInterval(_f, interval);
}
}
this.stop = function() {
if (this.running == true) {
this.running = false;
console.log(this + "(" + element + ") was stopped");
stopped = new Date;
interval = 1000 - (stopped - secondStarted);
clearInterval(ac);
}
}
this.getTotalTimeInSeconds = function() {
return finalTimeInSeconds;
}
this.reset();
}
function note(string) {
alert(string);
}
function mainMenu() {
//EMPTY BODY
$("body").empty();
$("body").append(
//BUTTONS
"<div id='playButton' class='mainButton'><div class='buttonText mainButtonText'>PLAY</div></div>"
);
//BINDS
$("#playButton").bind("click", function(){
playMain();
setUpSession();
});
}
function playMain() {
//EMPTY BODY
$("body").empty();
$("body").append(
//TASK TEXT
"<p class='text' id='taskText'>Lorem ipsum dolor sit amet.</p>",
//TIMERS
"<div id='taskTimerWrap'><p class='text timer' id='taskTimer'>00:00</p><p class='text' id='taskTimerText'>Task Time</p></div>",
"<div id='globalTimerWrap'><p class='text timer' id='globalTimer'>00:00</p><p class='text' id='globalTimerText'>Global Time</p></div>",
//TASK COUNTER
"<div class='text' id='taskCounter'>0/0 tasks completed</div>"
);
//BINDS
$("#taskText").bind("click", nextTask);
}
#taskText {
text-align: center;
display: table;
vertical-align: middle;
height: auto;
width: 100%;
top: 50px;
bottom: 0;
left: 0;
right: 0;
position: absolute;
margin: auto;
font-size: 65px;
cursor: pointer;
}
#taskTimerWrap {
text-align: center;
top: 0;
right: 0;
left: 170px;
margin: 5px;
position: absolute;
-webkit-transition: all 0.5s ease;
}
.timer {
font-size: 64px;
margin: 0;
line-height: 0.88;
}
#taskTimerText {
font-size: 34.4px;
margin: 0;
line-height: 0.65;
}
#globalTimerWrap {
text-align: center;
top: 0;
left: 0;
right: 170px;
margin: 5px;
position: absolute;
}
#globalTimerText {
font-size: 28.5px;
margin: 0;
line-height: 0.78;
transform: scale(1, 1.2);
}
#taskCounter {
text-align: center;
bottom: 0;
right: 0;
left: 0;
width: auto;
position: absolute;
font-size: 30px;
color: #98D8D9;
-webkit-transition: all 0.5s ease;
}
#taskCounter:hover {
color: #F1F2F0
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here is an update in jsfiddle
The problem is on the variable interval of Timer
This line creates unpredictable interval under Timer.stop():
interval = 1000 - (stopped - secondStarted);
If you would like to shorten the time interval, you can add a play_count property:
...
//timer object function
function Timer(element, callback) {
var ac, minutes, seconds, finalTimeInSeconds, displayMinutes, displaySeconds, interval = 1000,
self = this,
timeLeftToNextSecond = 1000;
this.running = false;
play_count = 0; // play count property
...
this.run = function() {
if (this.running == false) {
this.running = true;
var _f = function() {
secondStarted = new Date;
self.subtract(0, 1);
interval = Math.max(1000 - play_count * 100, 500); // ** <-- shorten time interval
}
ac = setInterval(_f, interval);
}
}
this.stop = function() {
if (this.running == true) {
this.running = false;
console.log(this + "(" + element + ") was stopped");
// stopped = new Date;
// interval = 1000 - (stopped - secondStarted);
play_count++;
clearInterval(ac);
}
}
this.getTotalTimeInSeconds = function() {
return finalTimeInSeconds;
}
this.reset();
}
...

how to display counter value into the output to start a countdown

I'm building a counter and have some issue with. I have a counter field where increment and decrement happen (by default it's 5 minutes). When 'start' button is pressed the final counter's digit should be set as the timer in the output field.
here is my solution:
;(function(){
var output = document.querySelector('#output'),
btn = document.querySelector('button'),
min = 5,
sec = min * 60,
timer;
setCount(min);
function setCount(n){
var c = document.querySelector('#counter'),
increment = c.children[1].children[0],
decrement = c.children[1].children[2],
num = c.children[1].children[1];
increment.onclick = function(){
if(n >= 1) {num.textContent = ++n;}
};
decrement.onclick = function(){
if(n > 1) {num.textContent = --n;}
};
num.textContent = n;
}
function setTimer(){
var currentMin = Math.round((sec - 30) / 60),
currentSec = sec % 60;
if(currentMin >= 0 ) {currentMin = '0' + currentMin;}
if(currentSec <= 9 ) {currentSec = '0' + currentSec;}
if(sec !== 0){sec--;}
timer = setTimeout(setTimer,10); // 10 is for the speedy
output.textContent = currentMin + ':' + currentSec;
}
btn.addEventListener('click', setTimer, false);
})();
here is the link : JS Bin
TL;DR
if(n >= 1) {num.textContent = ++n; sec = n * 60;} // Line 15
...
if(n > 1) {num.textContent = --n; sec = n * 60; } // Line 19
Your timer is deriving it's start min value from the seconds, which is always equal to 5 * 60. You need to update the seconds every time that the + or - is clicked.
(function() {
var output = document.querySelector('#output');
var btn = document.querySelector('button');
var min = 5;
var sec = min * 60;
var timer;
var counter = document.querySelector('#counter ul');
var increment = counter.children[0];
var decrement = counter.children[2];
var number = counter.children[1];
number.textContent = min;
increment.onclick = function() {
min++;
number.textContent = min;
sec = min * 60;
};
decrement.onclick = function() {
min--;
if (min < 1) {
min = 1;
}
sec = min * 60;
number.textContent = min;
};
function setTimer() {
var currentMin = Math.round((sec - 30) / 60),
currentSec = sec % 60;
if (currentMin == 0 && currentSec == 0) {
output.textContent = '00:00';
return;
} else {
timer = setTimeout(setTimer, 10);
}
if (currentMin <= 9) {
currentMin = '0' + currentMin;
}
if (currentSec <= 0) {
currentSec = '0' + currentSec;
}
if (sec !== 0) {
sec--;
}
output.textContent = currentMin + ':' + currentSec;
console.log('currentMin: ' + currentMin);
}
btn.addEventListener('click', setTimer, false);
})();
#wrapper {
width: 300px;
border: 1px solid #f00;
text-align: center;
}
#output {
height: 40px;
line-height: 40px;
border-bottom: 1px solid #f00;
}
h4 {
margin: 10px 0;
}
ul {
margin: 0;
padding: 0;
}
li {
list-style: none;
width: 40px;
height: 40px;
line-height: 40px;
display: inline-block;
border: 1px solid #f00;
}
li:nth-child(odd) {
cursor: pointer;
}
button {
padding: 5px 15px;
margin: 10px 0;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div id="wrapper">
<div id="output"></div>
<div id="counter">
<h4>counter</h4>
<ul>
<li>+</li>
<li></li>
<li>-</li>
</ul>
</div>
<button id="start">start</button>
</div>
</body>
</html>

Count-up Timer required

I've been wanting to create a timer for my website that countsup, and displays alerts at certain intervals. So like, it starts from 0 and counts upwards when the user pushes a button. From there, it will display a a custom alert at certain intervals... (4 minutes for example)... 45 seconds before that interval, I need the number to change to yellow and 10 seconds before that interval, I need it to change to red... then back to the normal color when it passes that interval.
I've got a basic timer code but I am not sure how to do the rest. I am quite new to this. Any help? Thanks so much in advance.
var pad = function(n) { return (''+n).length<4?pad('0'+n):n; };
jQuery.fn.timer = function() {
var t = this, i = 0;
setInterval(function() {
t.text(pad(i++));
}, 1000);
};
$('#timer').timer();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='timer'></div>
You could do something like this
var pad = function (n) {
return ('' + n).length < 4 ? pad('0' + n) : n;
};
jQuery.fn.timer = function () {
var t = this,
i = 0;
setInterval(function () {
t.text(pad(i++));
checkTime(i, t);
}, 1000);
};
$('#timer').timer();
checkTime = function (time, t) {
switch (time -1) {
case 10:
t.css('color','red');
break;
case 20:
t.css('color','yellow');
break;
case 30:
t.css('color','green');
break;
case 40:
t.css('color','black');
break;
default:
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='timer'></div>
Something like this should work:
Here is a jsFiddle DEMO
jQuery
$.fn.timer = function (complete, warning, danger) {
var $this = $(this);
var total = 0;
$this.text(total);
var intervalComplete = parseInt(complete, 10);
var intervalWarning = parseInt(intervalComplete - warning, 10);
var intervalDanger = parseInt(intervalComplete - danger, 10);
var clock = setInterval(function () {
total += 1;
$this.text(total);
if (intervalWarning === total) {
// set to YELLOW:
$this.addClass('yellow');
}
if (intervalDanger === total) {
// set to RED:
$this.removeClass('yellow').addClass('red');
}
if (intervalComplete === total) {
// reset:
clearInterval(clock);
$this.removeClass();
alert('COMPLETE!');
}
}, 1000);
};
$(function () {
$('#timer').timer(240, 45, 10);
});
CSS
.red {
background-color: red;
}
.yellow {
background-color: yellow;
}
An additional point:
You should place some error validation within the function to ensure your counter completion time is greater than both the warning and danger time intervals.
You can try something like this:
JSFiddle
This is a pure JS timer code. Also for popup you can use something like Bootbox.js.
Code
function timer() {
var time = {
sec: 00,
min: 00,
hr: 00
};
var finalLimit = null,
warnLimit = null,
errorLimit = null;
var max = 59;
var interval = null;
function init(_hr, _min, _sec) {
time["hr"] = _hr ? _hr : 0;
time["min"] = _min ? _min : 0;
time["sec"] = _sec ? _sec : 0;
printAll();
}
function setLimit(fLimit, wLimit, eLimit) {
finalLimit = fLimit;
warnLimit = wLimit;
errorLimit = eLimit;
}
function printAll() {
print("sec");
print("min");
print("hr");
}
function update(str) {
time[str] ++;
time[str] = time[str] % 60;
if (time[str] == 0) {
str == "sec" ? update("min") : update("hr");
}
print(str);
}
function print(str) {
var _time = time[str].toString().length == 1 ? "0" + time[str] : time[str];
document.getElementById("lbl" + str).innerHTML = _time;
}
function validateTimer() {
var c = "";
var secs = time.sec + (time.min * 60) + (time.hr * 60 * 60);
console.log(secs, finalLimit)
if (secs >= finalLimit) {
stopTimer();
} else if (secs >= errorLimit) {
c = "error";
} else if (secs >= warnLimit) {
c = "warn";
} else {
c = "";
}
var element = document.getElementsByTagName("span");
console.log(element, c)
document.getElementById("lblsec").className = c;
}
function startTimer() {
init();
if (interval) stopTimer();
interval = setInterval(function() {
update("sec");
validateTimer();
}, 1000);
}
function stopTimer() {
window.clearInterval(interval);
}
function resetInterval() {
stopTimer();
time["sec"] = time["min"] = time["hr"] = 0;
printAll();
startTimer();
}
return {
'start': startTimer,
'stop': stopTimer,
'reset': resetInterval,
'init': init,
'setLimit': setLimit
}
};
var time = new timer();
function initTimer() {
time.init(0, 0, 0);
}
function startTimer() {
time.start();
time.setLimit(10, 5, 8);
}
function endTimer() {
time.stop();
}
function resetTimer() {
time.reset();
}
span {
border: 1px solid gray;
padding: 5px;
border-radius: 4px;
background: #fff;
}
.timer {
padding: 2px;
margin: 10px;
}
.main {
background: #eee;
padding: 5px;
width: 200px;
text-align: center;
}
.btn {
-webkit-border-radius: 6;
-moz-border-radius: 6;
border-radius: 6px;
color: #ffffff;
font-size: 14px;
background: #2980b9;
text-decoration: none;
transition: 0.4s;
}
.btn:hover {
background: #3cb0fd;
text-decoration: none;
transition: 0.4s;
}
.warn {
background: yellow;
}
.error {
background: red;
}
<div class="main">
<div class="timer"> <span id="lblhr">00</span>
: <span id="lblmin">00</span>
: <span id="lblsec">00</span>
</div>
<button class="btn" onclick="startTimer()">Start</button>
<button class="btn" onclick="endTimer()">Stop</button>
<button class="btn" onclick="resetTimer()">Reset</button>
</div>
Hope it helps!

Click Counter in a Customized way

<script type="text/javascript">
var clicks = 0;
function onClick() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
};
</script>
<td><button type="button" onclick="onClick()" >0.1</td>
<p>Ball Count: <a id="clicks">0.0</a></p>
Hi I am trying to create customized click counter, when every 6th click it should go to the next whole number( Example: 0.1,0.2,0.3,0.4,0.5,1.0 (6th click),1.1,1.2,1.3,1.4,1.5,2.0(12th click) like wise) and how to decrease the same way... Kindly help me.....
Your requirement have some similarities to the time calculation. You can use the following.
jQuery version
var clicks = 0;
$('#plusClick, #minusClick').on('click', function () {
if( this.id == 'plusClick' )
clicks += 10;
else if( clicks > 0 )
clicks -= 10;
var first = Math.floor((clicks) / 60);
var second = clicks - (first * 60);
if (first < 10) {first = "0" + first;}
if (second < 10) {second = "0" + second;}
var value = first + '.' + second;
document.getElementById("clicks").innerHTML = parseFloat(value).toFixed(1);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="clicks">0.0</div>
<button id="minusClick">-</button>
<button id="plusClick">+</button>
JS version
var clicks = 0;
function onClick(operation) {
if( operation ){
clicks += 10;
} else if(clicks > 0){
clicks -= 10;
}
var first = Math.floor((clicks) / 60);
var second = clicks - (first * 60);
if (first < 10) {first = "0" + first;}
if (second < 10) {second = "0" + second;}
var value = first + '.' + second;
document.getElementById("clicks").innerHTML = parseFloat(value).toFixed(1);
}
<div id="clicks">0.0</div>
<button id="minusClick" onclick="onClick(false)">-</button>
<button id="plusClick" onclick="onClick(true)">+</button>
May be you are looking for something like this:
var a = 0;
function increase() {
if (a % 10 == 5)
a += 5;
else
a++;
return a / 10;
}
function decrease() {
if (a % 10 == 0)
a -= 5;
else
a--;
return a / 10;
}
Note that I have used a Global Variable for this, which is not recommended.
Snippet, without global values.
var counter = {
currentValue: 0
};
function increase() {
var a = counter.currentValue;
if (a % 10 == 5)
a += 5;
else
a++;
counter.currentValue = a;
return a / 10;
}
function decrease() {
var a = counter.currentValue;
if (a % 10 == 0)
a -= 5;
else
a--;
counter.currentValue = a;
return a / 10;
}
input {border: 1px solid #999; padding: 5px; width: 15px; height: 15px; text-align: center; font-family: 'Segoe UI'; line-height: 1; width: 50px;}
input[type=button] {padding: 0; vertical-align: top; width: 35px; height: 27px;}
<input type="button" value="-" onclick="currentCount.value = decrease();" />
<input type="text" id="currentCount" value="0" />
<input type="button" value="+" onclick="currentCount.value = increase();" />
Just change onclick() with
function onClick(){
clicks += 1;
var a = Math.floor(clicks/6);
var b = (clicks%6);
document.getElementById("clicks").innerHTML = a + '.' + b;
}
Try to make use of mathematics not some school boy logic,
function increment(val) {
++val;
$("button").data("count", val);
return (val + (Math.floor((val / 6)) * 4)) / 10;
}
$("button").click(function () {
$('input').val(increment(parseFloat($(this).data("count"))));
});
DEMO

How to stop Looping - Javascript 100%

I was hoping someone could help me figure this out. I will list the code, and it works just fine, as it is an animation. However, when I check it out in the console it wont stop looping even though it hit the last item in the array. The image itself stops, but if you view the console it shows it looping.
Here is the code, have at it!
var position_X = ["0px", "-525px", "-1050px", "-1575px", "-2100px", "-2625px", "-3150px", "-3675px", "-4200px", "-4725px", "-5250px", "-5775px", "-6300px", "-6825px", "-7350px"];
var _lock = document.getElementById('hi');
// console.log(_lock);
_lock.style.border = "1px solid black";
_lock.style.backgroundImage = "url('http://handbagmanufacturing.com/wp-content/CDN/images/lock.png')";
function lockAnimation(){
setInterval(function(){
var _count = position_X.length;
for(var i = 0; i < _count; i++){
if(i == _count) break;
_lock.style.backgroundPosition = position_X[i] + " 263px";
console.log("Here is the background positions : " + i + ") " + position_X[i]);
}
}
, 100);
}
#hi {
width: 525px;
height: 263px;
background-position-x: "-7875px"
}
<button onclick="lockAnimation()">Click Me I'm Irish!</button>
<div id="hi"></div>
Change setInterval to setTimeout. This will run the function only once instead of running it every 100 ms.
var position_X = ["0px", "-525px", "-1050px", "-1575px", "-2100px", "-2625px", "-3150px", "-3675px", "-4200px", "-4725px", "-5250px", "-5775px", "-6300px", "-6825px", "-7350px"];
var _lock = document.getElementById('hi');
// console.log(_lock);
_lock.style.border = "1px solid black";
_lock.style.backgroundImage = "url('http://handbagmanufacturing.com/wp-content/CDN/images/lock.png')";
function lockAnimation(){
setTimeout(function(){
var _count = position_X.length;
for(var i = 0; i < _count; i++){
if(i == _count) break;
_lock.style.backgroundPosition = position_X[i] + " 263px";
console.log("Here is the background positions : " + i + ") " + position_X[i]);
}
}
, 100);
}
#hi {
width: 525px;
height: 263px;
background-position-x: "-7875px"
}
<button onclick="lockAnimation()">Click Me I'm Irish!</button>
<div id="hi"></div>

Categories