JS Math setinterval a random number from a range - javascript

I have a default number and after the page loads, after each second, I have to add to it a number from this range: (0.02 - 0.006).
Here is the code:
var amount = 44522.1234;
setTimeout(start, 1000);
var i = Math.floor(Math.random() * (0.02 - 0.006) + 0.006);
console.log("initial" + i);
var num = document.getElementById('total');
function start() {
setInterval(increase, 1000);
}
function increase() {
if (i < amount) {
i++;
console.log(i);
num.innerText = amount + i;
}
}
<div id="total"></div>
The above code only increments the amount by 1 each second, instead of by a number in the specified range.

Math.floor will truncate the number, so it will never be in the range you want. Also, you should generate a new random number every second instead of incrementing the originally generated number.
var amount = 44522.1234;
setTimeout(start, 1000);
var num = document.getElementById('total');
function start() {
setInterval(increase, 1000);
}
function increase() {
var i = Math.random() * (0.02 - 0.006) + 0.006;
console.log("adding",i);
amount += i;
num.textContent = amount;
}
<div id="total"></div>

Related

Addition of two random number, with a different setTimeout ( Code almost working )

I made a simple code to add two random numbers.
Number 1 is minimum 1000 and maximum 2000.
It changes every 10 seconds.
Number 2 is minimum 1 and maximum 5.
It changes much faster ( delay is random )
The point is to addition number 1 + number 2, and "refresh" the total everytime number 2 changed.
Thanks in advance :)
function bignumber() {
var bignumber = 1000 + Math.floor(Math.random() * 1000);
$('#bignumber').text(bignumber);
return bignumber;
setTimeout(Big, 2300);
}
bignumber()
function addition() {
var rand = Math.floor(Math.random() * (10 - 5 + 1) + 5);
var smallnumber = Math.floor(Math.random() * (5 - 1 + 1) + 1);
var result = ??How to place Number1 here?? + smallnumber;
$('#smallnumber').text(result);
setTimeout(myFunction, rand * 300);
}
addition()
You have to define var bignumber outside function scope and update its value on function one also read value in function two
var bignumber =0 ;
function bignumber() {
bignumber = 1000 + Math.floor(Math.random() * 1000);
......
function addition() {
....
var result = bignumber + smallnumber;
...`

Modify Countup Timer To Include Currency Formatting In Javascript

I have a simple countup timer that takes a starting number and randomly counts up. However, it doesn't work correctly on numbers that include decimals and commas.
How can I modify this to count up correctly in cents?
For example I want to count starting at the number 1,234,567.15 and every 500 milliseconds it adds a random amount of cents to the end. Then when it goes over 99 it adds to the dollar value.
Current Usage:
<span>$</span><span id="counter">1,234,567.15</span>
Javascript:
<script>
var timer;
function startCount() {
timer = setInterval(count, 500); // 200 = 200ms delay between counter changes. Lower num = faster, Bigger = slower.
}
function count() {
var do_wait = Math.ceil(4 * Math.random());
if (do_wait == 4) {
var rand_no = Math.ceil(4 * Math.random()); // 4 = random decrement amount. Counter will decrease anywhere from 1 - 4.
var el = document.getElementById('counter');
var currentNumber = parseFloat(el.innerHTML);
var newNumber = currentNumber + rand_no;
if (newNumber < 99999999999) {
el.innerHTML = newNumber;
}
}
}
startCount();
</script>
parseFloat doesn't process ',' ,it will stop parse will met ',';
the best way is to use newNumber.toLocaleString()
var timer;
function startCount() {
timer = setInterval(count, 500); // 200 = 200ms delay between counter changes. Lower num = faster, Bigger = slower.
}
function count() {
var do_wait = Math.ceil(4 * Math.random());
if (do_wait == 4) {
// var rand_no = Math.ceil(4 * Math.random()); // 4 = random decrement amount. Counter will decrease anywhere from 1 - 4.
var rand_no = 4 * Math.random(); //if you also want cents change,take this and comment previous line
var el = document.getElementById('counter');
var currentNumber = parseFloat(el.innerHTML.replace(/,/g, ''));
var newNumber = currentNumber + rand_no;
if (newNumber < 99999999999) {
el.innerHTML = Number(newNumber.toFixed(2)).toLocaleString();
}
}
}
startCount();
<span>$</span><span id="counter">1,234,567.15</span>
if not work ,process it manually:
replace ',' to '' and calculate the number and add ',' back:
var timer;
function startCount() {
timer = setInterval(count, 500); // 200 = 200ms delay between counter changes. Lower num = faster, Bigger = slower.
}
function count() {
var do_wait = Math.ceil(4 * Math.random());
if (do_wait == 4) {
// var rand_no = Math.ceil(4 * Math.random()); // 4 = random decrement amount. Counter will decrease anywhere from 1 - 4.
var rand_no = 4 * Math.random(); //if you also want cents change,take this and comment previous line
var el = document.getElementById('counter');
var currentNumber = parseFloat(el.innerHTML.replace(/,/g, ''));
var newNumber = currentNumber + rand_no;
if (newNumber < 99999999999) {
el.innerHTML = processNumber(newNumber);
}
}
function processNumber(num) {
let strArr = num.toFixed(2).split('.')[0].split(/|/g).reverse();
let result = strArr.map(function(v, index) {
return index % 3 === 0 ? v + ',' : v;
}).reverse();
return result.join('').replace(/,$/, '.') + num.toFixed(2).split('.')[1];
}
}
startCount();
<span>$</span><span id="counter">1,234,567.15</span>

Add random number at Random time intervals

The thing is I want to add random number to a variable which is initially 0 which has to happen after a random timeout until the variable reaches 100.
$scope.var1 = 0;
do{
$timeout(function(){
$scope.var1 += Math.floor(Math.random() * 100 +1);
},Math.floor(Math.random() * 100 +1));
console.log($scope.var1);
}while($scope.var1<100)
$scope.var1 always stays 0, hence it goes to an infinite loop;
You get inifinity loop since $timeout function, that you use, is async, but your loop is sync. You have to use recursion:
$scope.var1 = 0;
function recursiveTimeout(){
$timeout(function(){
if($scope.var1 < 100){
$scope.var1 += Math.floor(Math.random() * 10 + 1);
console.log($scope.var1);
recursiveTimeout()
}
}, Math.floor(Math.random() * 1000 + 1));
}
recursiveTimeout()
http://jsfiddle.net/dwypcx1f/3/
Math.random is a JS function, so it has to be Math.floor(Math.random() * 100 +1); instead of Math.floor(Math.random * 100 +1);
I didn't checked the rest of your code.
You start a new loop on every loop iteration. I am not sure about the correct AngularJS syntax since I prefer Angular2, but something like this should work...
$scope.var1 = 0;
var repeatFunc = function repeatFunc() {
var num = Math.floor(Math.random() * 100 +1);
$scope.var1 += num;
console.log("num: ", num);
if ($scope.var1 < 100)
$timeout(repeatFunc, num);
}
repeatFunc();

Trying to get timer to start once arrived on the page

I made the following fiddle of what I have right now..
https://jsfiddle.net/r5yj99bs/1/
I'm trying to start right when I get onto a page, but allowing the option to leave the pause/resume option. Then is there anyway to display the remaining time as '5 minutes' instead of '300 seconds' and then count down that way rather than only seconds.
<button class="start-pause">Start</button>
<h2 class="time-left"></h2>
var times = [];
var counter_interval;
var $time_left = $('.time-left');
var $button = $('.start-pause');
// timer length in seconds
var timer_length = 300;
$('body').on('click', '.start-pause', function() {
// are we starting or stopping?
var starting = times.length % 2 == 0;
times.push(Date.now());
if (starting) {
$button.html('Pause');
counter_interval = setInterval(function() {
var time_left = Math.floor(timer_length - sum_elapsed());
if (time_left < 1) {
clearInterval(counter_interval);
return finished();
}
$time_left.html(time_left);
}, 100);
} else {
$button.html('Resume');
clearInterval(counter_interval);
}
});
var sum_elapsed = function() {
sum = 0;
for (var i=0; i<times.length; i++) {
if (i % 2 == 1) {
sum += (times[i] - times[i-1]);
}
if (i == (times.length - 1)) {
sum += (Date.now() - times[i]);
}
}
// convert milliseconds to seconds
return sum / 1000;
};
var finished = function() {
$button.attr('disabled','disabled').html('Finished');
$time_left.html("Time's Up");
};
There is a good time module called moment. You can get it through npm or from moments.com
That can format relative time to human readable strings.
If you want to do it yourself, take the seconds modulus 60 to get the minutes. Using modulus you can extract all info about hours and so on.
You may change the following line:
$time_left.html(time_left);
to:
$time_left.html(secToMinTxt(time_left));
and add the following functions:
function pad(num) {
var str = "" + num;
var pad = "00";
return pad.substring(0, pad.length - str.length) + str;
}
function secToMinTxt(seconds) {
var min = Math.floor(seconds / 60);
var sec = seconds % 60;
return pad(min) + ":" + pad(sec);
}
JSFiddle reference : https://jsfiddle.net/r5yj99bs/2/
If interpret Question correctly, try using Math.round with argument existing time_left variable divided by 60
var time_left = Math.round(Math.floor(timer_length - sum_elapsed()) / 60);
jsfiddle https://jsfiddle.net/r5yj99bs/3/

Howto run function every few seconds that has return values?

How can I run this every few second , without blocking the rest of the pagefrom loading.
function Create() {
var SomeArray = [];
for ( var i=0; i<=1 ; i ++) {
SomeArray[i] = (Math.random() * 10) + 1;
//alert(arr[0]);
}
return SomeArray;
}
var x = Create();
alert(x[0] + x[1]);
I was trying this var timer = setInterval(Create, 5000); it prevent loading rest of the page.
i want to get new values every few seconds
A basic example would be:
var counter = 0;
var timerRef;
var increment = function() {
counter += 1;
console.log(counter);
timerRef = setTimeout(increment, 1000);
}
setTimeout(increment, 1000);
// clearTimeout(timerRef);
Please avoid document.write refer the screencast for further details.
setInterval() can be configured to repeatedly call any function you designate at whatever time interval you request. But, you can't retrieve a return value from that function. Instead, you need to process the results from within the callback that you pass to setInterval() or call some other function and pass the results you generate inside the callback. This is how asynchronous functions work in JavaScript. I've provided several examples below of your options:
If you just want to generate two random decimal values between 1 and 10 (inclusive) every 5 seconds, you can do that like this:
var interval = setInterval(function() {
var rand1 = (Math.random() * 10) + 1;
var rand2 = (Math.random() * 10) + 1;
// now insert code here to do something with the two random numbers
}, 5000);
If you wanted the random values to be integers (which is more common), then you would do this:
var interval = setInterval(function() {
var rand1 = Math.floor(Math.random() * 10) + 1;
var rand2 = Math.floor(Math.random() * 10) + 1;
// now insert code here to do something with the two random numbers
}, 5000);
If you want to call a function and pass it those two random numbers, you can do this:
function processRandoms(r1, r2) {
// code here to do something with the two random numbers
}
var interval = setInterval(function() {
var rand1 = Math.floor(Math.random() * 10) + 1;
var rand2 = Math.floor(Math.random() * 10) + 1;
processRandoms(rand1, rand2);
}, 5000);
You can then stop the recurring interval at any time with this:
clearInterval(interval);

Categories

Resources