Trying to make a simple count up timer in jQuery... this sort of works but is adding the numbers to the end of '0000' and I want it to go '0001' '0002' '0003' etc...
This is all happening in the jQuery onReady scope.
var i = '0000'
var timer = function doSomething ( )
{
i = i+= 1
$('.counter').text(i);
console.log(i);
}
setInterval (timer, 1000 );
Your "i" variable needs to be an integer. You can format it how you like when you want to print it somewhere.
$(document).ready(function() {
var i = 0;
var target = $('.counter');
var timer = function doSomething ( )
{
i++;
var output = pad(i,4);
target.text(output);
console.log(output);
}
setInterval (timer, 1000 );
});
function pad(number, length) {
var str = '' + number;
while (str.length < length) {
str = '0' + str;
}
return str;
}
Your current code is appending to a string, not addition to a number. It essentially looks like
i = '0000' + 1, i = '00001' + 1, i = '000011' + 1 ...
and so on. You'll need to keep it integer based to continue adding to the number. Here's an example with the formatting it looks like you wanted.
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();
http://jsfiddle.net/jDaTK/
I would do something more like this:
// Make sure Date.now exists in your environment
Date.now = Date.now || function () { return Number(new Date()); };
var time = 0,
start = Date.now(),
intervalId;
intervalId = setInterval(function () {
var seconds, display;
// get the exact time since the timer was started
time = Date.now() - start;
// get the number or seconds, rounded down
seconds = Math.floor(time / 1000);
display = '' + seconds;
// pad the beginning of your display string with zeros
while (display.length < 4) {
display = "0" + display;
}
console.log(display);
}, 100);
setInterval is not exact. This code ensures that while the display could be up to nearly a second off (in theory), the actual time you are tracking is always the exact amount of time that has elapsed since you started the timer. But this code would update the display about once every tenth of a second, so it's not likely to ever be off more than a few milliseconds.
From here you can figure out smarter ways to update the display to ensure you have the level of accuracy you need. If this needs to be pretty accurate, then you could make sure you are displaying to the tenth of the second.
I really recommend the jQuery CountUp plugin. I tried a number of Javascript counters and this was one of the easiest to implement and came with lots of goodies:
<script type="text/javascript">
$(document).ready(function(){
$('#counter').countUp({
'lang':'en', 'format':'full', 'sinceDate': '22/07/2008-00::00';
});
});
</script>
<div id="counter"></div>
Related
I am trying to make a function that will only retain its variable count from the past minute.
For example, if I call function count 100 times, if 60 of those calls were from the past minute, it will only return 60, and not 100.
This is what I have tried so far, making the variable an array and adding numbers to it everytime its called, but I do not know how to remove a count when a minute has passed.
var count = 1;
var countArray = [];
UPDATE:
I have updated my code with this, but the array elements are not removing as they should,
function Count() {
var jNow = new Date();
jCountArray.push(jNow);
for (var i = 0; i <= jCountArray.length; i++) {
var secondsDiff = (new Date(jNow).getTime() - new Date(jCountArray[i]).getTime()) / 1000;
if (secondsDiff >= 10) { jCountArray.shift(); }
}
console.log(jCountArray);
return jCountArray.length;
}
If I understand your requirements correctly, and the only thing you need Count to do is return how many times it was called in the last minute, I think we could do something relatively easily leveraging setTimeout:
function getCounter() {
let count = 0;
let duration = 60000;
return function () {
count = count + 1;
setTimeout(function () {
count = count - 1;
}, duration);
return count;
}
}
let counter = getCounter();
function count() {
console.log(counter());
}
<button onclick="count()">Count</button>
The only trick here is, to keep the actual count private, we need a factory function to wrap it in a closure. If that's unimportant you can write it as a simple function and keep the count in the parent scope. Also, for testing purposes you can change the duration to a lower millisecond count to see it in action.
I want to make a countdown in javascript, with simple variables, for loop, set timeout.
I get stuck when trying to make a for loop update realtime (every second) right now I get -1 in webpage.
//HTML PART
<p id=timer>0</p>
//JS PART
var timer = 10;
var text = "";
function f() {
for (timer; timer > 0; timer--) {
text += timer + "<br>";
}
timer--;
if( timer > 0 ){
setTimeout( f, 1000 );
}
}
f();
document.getElementById("timer").innerHTML = timer;
Please explain the error and if I'm doing any stupid mistakes
Looks like you want to show timer value from 10 to 0 by changing the value every second. If so, you can do like this:
1. You need to correct your html by putting quotes around timer like this <p id="timer">0</p>
2. You need to remove for loop as I have commented.
3. Move document.getElementById("timer").innerHTML = timer; inside function f().
var timer = 10;
//var text = "";
function f() {
//for (timer; timer > 0; timer--) {
// text += timer + "<br>";
//}
document.getElementById("timer").innerHTML = timer;
timer--;
if (timer >=0) {
setTimeout(f, 1000);
}
}
f();
<p id="timer">0</p>
You can do it like so, I provided comments in code for explanation:
var count = 10;
function timer(targetValue) {
// display first number on screen
document.getElementById("timer").textContent = count;
// decrease count by 1
count--;
// check if timer is still grater than target value
if (count >= targetValue) {
// call timer() function every second to update
setTimeout(timer, 1000, targetValue);
}
}
timer(0);
Counts down from 10 to 0.
Want to count down from 10 to 5? Simply use timer(5)
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.
So I've got this counter and it needs to increment a number by 75 every 60 seconds. The code I have below does this fine but due to rounding some numbers stay up longer than others, and some numbers are skipped.
I'd rather have this to smoothly/evenly count to get the same end result. I know I would need to somehow calculate the setInterval timer number, but I'm not sure what to get that.
(function(){
//Numbers
var num = 0;
var perMinute = 75;
var perSecond = perMinute / 60;
//Element selection
var count = document.getElementById("count");
function update(){
//Add the per-second value to the total
num += perSecond;
//Display the count rounded without a decimal
count.innerHTML = Math.round(num);
}
//Run the update function once every second
setInterval(update, 1000);
})();
Working example: http://jsfiddle.net/ChrisMBarr/9atym/1/
Never rely on Timeout or Interval to be accurate. Instead, save the "start time" and compare it to the current time.
(function() {
var start = new Date().getTime(),
perMinute = 75,
perMS = perMinute/60000,
count = document.getElementById('count');
function update() {
var elapsed = new Date().getTime()-start;
count.innerHTML = Math.round(elapsed*perMS);
}
setInterval(update,1000);
})();
Note that you can adjust the 1000 to vary "smooth" the counter is (more important for bigger values of perMinute) and it will always work perfectly, to within the resolution's overshoot.
Moving your rounding seemed to fix this (Edit: No it doesn't. See the jsfiddle example of a better fix I put below).
(function(){
//Numbers
var num = 0;
var perMinute = 75;
var perSecond = perMinute / 60;
//Element selection
var count = document.getElementById("count");
function update(){
//Add the per-second value to the total
num += Math.round(perSecond);
//Display the count rounded without a decimal
count.innerHTML = num;
}
//Run the update function once every second
setInterval(update, 1000/perSecond);
})();
Edit: a proper fix - http://jsfiddle.net/4y2y9/1/
I have a JSON array(?) of pairs of every state and a value associated with that state, it looks like the following below:
var states = [{"STATE":"AL","AMOUNT":"6"}, {"STATE":"AK","AMOUNT":"3"}]
I need the page to shuffle through them without reloading the page
"AL 6" [wait x seconds] then "AK 3" [wait x seconds] then etc...
I need this to run continuously.
I never use any of these languages but was told that they were my best bet.
Could someone give me some guidance on this please.
Thank you in advance.
Here's a jsfiddle with setInterval execting a function that alternates between each state and displays it in a div:
http://jsfiddle.net/WD5Qj/1/
var states = '[{"STATE":"AL","AMOUNT":"6"}, {"STATE":"AK","AMOUNT":"3"}]';
json = jQuery.parseJSON(states);
var i = 0;
var cycle = function(){
$("#state").html(json[i].STATE + json[i].AMOUNT);
i = (i+1)%json.length;
}
var loop = setInterval(cycle, 500);
Alright, you'd need a function that does the rotation through the array, and a variable for keeping the current state (in both meanings of the word):
var stateIndex = 0;
function rotate() {
stateIndex++;
if(stateIndex >= states.length)
stateIndex = 0;
displayState(states[stateIndex]);
}
And you'd need an interval to perform the rotation:
var stateRotation = window.setInterval(rotate, 3000); // 3000ms = 3 sec
The stateRotation variable is an identifier of your interval. You may use that if you ever want to stop: window.clearInterval(stateRotation);
Now, the above code anticipates a function displayState which takes a state object and displays it. How that would look depends entirely on how you want your state to displayed. In its simplest form, something like this:
function displayState(state) {
$('#state-name').html(state.STATE);
$('#state-amount').html(state.AMOUNT);
}
As per your description, it might perhaps be something more like
$('#state-text').html(state.STATE + ' ' + state.AMOUNT);
var states = [{"STATE":"AL","AMOUNT":"6"}, {"STATE":"AK","AMOUNT":"3"}];
var i = 0;
setInterval(function(){
var array_index = i % states.length;
$('#state').html( states[ array_index ]['STATE'] );
$('#state').html( states[ array_index ]['AMOUNT'] );
i++;
}, 2000);
Here's a fiddle.
function displayNextItem(index){
if (index === states.length)
displayNextItem(0);
$("#someDiv").text(states[index]["STATE"] + " " + states[index]["AMOUNT"]);
setTimeout(function() { displayNextItem(index + 1); }, 1000);
}
And then
displayNextItem(0);
var i = 0, l = states.length, timer, intervalLength = 5000;
timer = setInterval(function(){
if(i >= l){
clearInterval(timer);
}else{
alert(states[i++].STATE);
}
},intervalLength);
This implementation is waiting the AMOUNT number of seconds. If you want constant number of seconds then other answers are better :).
JavaScript:
var states = [{"STATE":"AL","AMOUNT":"6"}, {"STATE":"AK","AMOUNT":"3"}];
function iterate(index) {
var time = states[index].AMOUNT;
// replace the text with new one
$("#output").text(states[index].STATE + " " + time);
setTimeout(function() {
var next = (index + 1) % states.length;
iterate(next);
}, time * 1000);
}
iterate(0);
HERE is the code.