i have spend an hour trying to find such a script to no avail
I want a simple countdown that starts at 200 units and decreases by a random increment between 0-3 units every second
var count = 200;
var timer = setInterval(function() {
count -= Math.floor(Math.random()*3);
if( count <= 0) {
count = 0;
clearInterval(timer);
}
},1000);
Related
New to JS, please be nice.
In creating a Javascript score for a browser canvas game, the code below increases by 1 for each second. For the variable score to equal 100, how would I go about this function displaying a window alert for when it reaches this value?
Attempts similar to if(score == 100); alert(score) have not worked for me.
Below code will not currently work in JSFiddle, output displays in browser tab.
var start = new Date().getTime(),
score = '0.1';
window.setInterval(function() {
var time = new Date().getTime() - start;
score = Math.floor(time / 1000) ;
if(Math.round(score) == score)
{ score += '.0 Score'; }
document.title = score;
}, 100);
You might want to clear the interval when you are done. Otherwise the interval continues on executing and very soon the score is no longer 100 (or whatever the upper limit will be)
Something along the lines of:
var start = new Date().getTime(),
score = '0.1';
// get handle to interval function
var interval = window.setInterval(function() {
var time = new Date().getTime() - start;
score = Math.floor(time / 1000);
console.log(score);
if (score >= 5) { // set to 5 for speedier test/check
score += '.0 Score';
window.clearInterval(interval); // clear interval to stop checking
alert(score);
}
document.getElementById('title').innerHTML = score; // display it
document.title = score;
}, 100);
<div id="title"></div>
I have a page that runs reloadData() function every 5 seconds:
setTimeout('reloadData()', 5000);
I have an element that I'd like to update with a countdown from 5 to 0 for every second of the reloadData();
document.getElementById('countdown').value
What is the proper way to do achieve this effect?
Example:
reloadData() {} starts
Element "countdown" will show: 5... 4... 3...
2... 1... (at second intervals)
reloadData(){} starts again
I'm not completely sure how to interpreter your question, but I guess you have a function reloadData which should run every 5 second.
You will now have a counter showed which will found from 5..1 for each second.
When then counter reaches 0 you want to repeat, eg calling reloadData() and count again?
var counter = 0;
setInterval(function() {
if (counter == 0) {
reloadData();
}
// do stuff with i which will be 0, 1, 2, 3, 4, 0, 1, 2, 3, 4
// ...
document.getElementById('countdown').value = 5 - counter;
// ...
counter++;
counter %= 5;
}, 1000);
More like 6 seconds because I hang out on reload for a bit, but you can use requestAnimationFrame to call your function (about 60 times a second) and check the date to see if you're over a second. Then update your counter.
As in this example:
https://jsfiddle.net/subterrane/k2aacj4s/
Output div:
<div class="container" id="counter"></div>
Some script:
var counter = document.querySelector("#counter");
var count = 5;
var start = Date.now();
function work() {
if (count == 0) {
counter.innerText = "reload!";
} else {
counter.innerText = count;
}
var now = Date.now();
if (now >= start + 1000) {
start = now;
count--;
if(count < 0) count = 5;
}
window.requestAnimationFrame(work);
};
work();
I am trying to increment from 0 to a number (can be any number from 2000 to 12345600000) within a certain duration (1000 ms, 5000 ms, etc). I have created the following:
http://jsfiddle.net/fmpeyton/c9u2sky8/
var counterElement = $(".lg-number");
var counterTotal = parseInt(counterElement.text()/*.replace(/,/g, "")*/);
var duration = 1000;
var animationInterval = duration/counterTotal;
counterElement.text("0");
var numberIncrementer = setInterval(function(){
var currentCounterNumber = parseInt(counterElement.text()/*.replace(/,/g, "")*/);
if (currentCounterNumber < counterTotal){
currentCounterNumber += Math.ceil(counterTotal/duration);
// convert number back to comma format
// currentCounterNumber = addCommas(currentCounterNumber);
counterElement.text(currentCounterNumber);
} else {
counterElement.text(counterTotal);
clearInterval(numberIncrementer);
}
console.log("run incrementer");
}, animationInterval);
function addCommas(number){
for (var i = number.length - 3; i > 0; i -= 3)
number = number.slice(0, i) + ',' + number.slice(i);
return number;
}
And this somewhat works, but it does not respect the duration. I.e. if you increase the number from 1000 to 1000000000, they both take different amounts of time to reach the destination number.
How can I increment from zero to a number in a specific time frame?
As #Mouser pointed out, the issue is that the animationInterval can't be too small (the actual minimum threshold will vary based on the browser and platform). Instead of varying the interval, vary the increment to the counter:
var counterElement = $(".lg-number");
var counterTotal = parseInt(counterElement.text()/*.replace(/,/g, "")*/);
var duration = 1000;
var animationInterval = 10;
var startTime = Date.now();
counterElement.text("0");
var numberIncrementer = setInterval(function(){
var elapsed = Date.now() - startTime;
var currentCounterNumber = Math.ceil(elapsed / duration * counterTotal);
if (currentCounterNumber < counterTotal){
counterElement.text(currentCounterNumber);
} else {
counterElement.text(counterTotal);
clearInterval(numberIncrementer);
}
console.log("run incrementer");
}, animationInterval);
I played around with your fiddle and found that the delay needs to be higher. At 8ms or 16ms, it is accurate enough to handle a second, but not accurate enough to handle half a second. From experimenting, it seems like a delay of 64ms is small enough to seem like it's incrementing smoothly, but big enough to have an accurate effect.
The difference is that the current number is calculated based on the process rather than directly manipulated.
var counterElement = $(".lg-number");
var counterTotal = parseInt(counterElement.data('total'));
var interval = 0;
var duration = parseInt(counterElement.data('duration'));;
var delay = 64
var numberIncrementer = setInterval(function(){
var currentCounterNumber = 0;
interval += delay;
if (interval <= duration){
var progress = interval / duration;
currentCounterNumber = Math.round(progress * counterTotal);
} else {
currentCounterNumber = counterTotal
clearInterval(numberIncrementer);
}
counterElement.text(currentCounterNumber);
}, delay);
http://jsfiddle.net/c9u2sky8/5/
Also: Javascript timers are not perfectly accurate. But this should be accurate enough for UI use cases.
Forgive me if this sounds a little confusing ... I am trying to adjust the value of a progress bar based on my randomize variable.
var randomize = Math.round(Math.random() * (3000 - 2000) + 1000);
How do I then get javascript to count from 0 to 'randomize' in seconds, so that I can apply it to my progress bar?
You could do something like this:
var randomize = Math.round(Math.random() * (3000 - 2000) + 1000);
var counter = 0;
var timer = setInterval( function(){
if ( counter <= randomize ){
// update progress bar
counter += 1;
}else{
clearInterval( timer );
}
}, 1000 );
Basically what I'm doing here is setting up a function to be called every second ( 1000 = 1 second in JavaScript). The timer will check if the counter variable has reached the value of randomize and if not, it will increment it's value by one.
Once counter is equal to randomize, the timer will be cleared.
References -
setInterval()
clearInterval()
var seconds = 0;
var timer = setInterval(function() {
seconds = seconds + 1;
if (seconds == randomize) {
clearInterval(timer);
}
}, 1000);
What is the best way to count from one preset number to a higher or lower number on input, and show the animation of the change?
There will be an initial amount, let say 100; and when we give it an increased or decreased number, let's say 200, the original 100 will count up animated to 200.
You can use setInterval like this:
var count = 100;
var number = 110;
var interval = setInterval(function(){
document.getElementById('elementID').innerHTML = ++count;
if (count === number) { clearInterval(interval) }
}, 500);
Use ++count if you want to increase or --count if you want to decrease.
Working Example
Not 100% sure I understand what you mean, but the count thing is simple:
function count() {
var i; //declare i for use later in the function
for (i = 100; i <= 200; i++) {
alert(i);
}
}