Is there any way to increase a number by 1 after random seconds.
For example, the base value is 10. So it will change by 1 after a random seconds(ie. 1/2/3/4/5 seconds randomly).
i have tried like this:
var startVal = 10;
setInterval(function(){
var theVal = startVal + 1;
startVal = theVal;
}, Math.round(Math.random() * (6000 - 2000)) + 2000);
Number is increasing but the time is not random. Please help.
If you want the time to change on each iteration, you will need to use setTimeout.
var startVal = 10;
function increase() {
setTimeout(function(){
var theVal = startVal + 1;
startVal = theVal;
increase();
console.log(startVal);
}, Math.round(Math.random() * (6000 - 2000)) + 2000);
}
increase()
Here is a working example. Will raise the number by one after 0,1 or 2 seconds
let number = 10;
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
function addNumber() {
number++;
console.log(number)
}
setTimeout(addNumber, getRandomInt(3) * 1000)
Related
So I'm trying to increment the value of a number in an interval of 1 second with a decimal number between (0.01 and 0.05) and I can't seem to figure this out.
The only thing that it does is to show me numbers between 0.01 and 0.05 instead of adding them up to be an integer.
setInterval (function myFunction() {
var number = 0;
document.getElementById("computerScore").innerHTML = number +
Math.floor((Math.random() * 5) + 1)/100;
}, 1000)
<b>computer score:</b><p id="computerScore">0</p>
Your problem is that you are setting number to 0 in each execution, while it should be the current value.
You need to assign Number(document.getElementById("computerScore").textContent) to it, so it keeps updating with the added random number.
Note that I used textContent which is recommended here as it holds only the text content of the element avoiding HTML elements.
setInterval (function myFunction() {
var number = Number(document.getElementById("computerScore").textContent);
document.getElementById("computerScore").textContent= number +
Math.floor((Math.random() * 5) + 1)/100;
}, 1000)
Demo:
setInterval (function myFunction() {
var number = Number(document.getElementById("computerScore").textContent);
document.getElementById("computerScore").textContent = number +
Math.floor((Math.random() * 5) + 1)/100;
}, 1000)
<b>computer score:</b><p id="computerScore">0</p>
You need to retrieve the previous value from your score and add your random Number to it :
PS: I added .toFixed(2) to limit your result to two decimals.
let score = document.getElementById("computerScore");
setInterval (function myFunction() {
score.innerHTML = (+score.innerHTML + Math.floor((Math.random() * 5) + 1)/100).toFixed(2);
}, 1000)
<b>computer score:</b><p id="computerScore">0</p>
You set number to 0 every time you call the function, you should define number outside of the interval
var number = 0;
setInterval(function myFunction() {
document.getElementById("computerScore").innerHTML = number +
Math.floor((Math.random() * 5) + 1) / 100;
}, 1000)
You need to declare number outside the setTimeout:
var number = 0;
setInterval (function myFunction() {
number = number +
Math.floor((Math.random() * 5) + 1)/100;
document.getElementById("computerScore").innerHTML = number;
}, 1000)
JSFiddle
you can try something like this. You forgot to set the number to 0. Then you have to increment your number with the random value you're getting.
https://codepen.io/anon/pen/dgJpep
JS :
var number = 0;
function check(){
setInterval(function(){
number = number + Math.floor((Math.random() * 5) + 1)/100;
}, 3000);
}
check();
setInterval(function(){
document.getElementById('computerScore').innerHTML = number;
});
Let me know if it works for you !
How can I return a random number in javascript which is always greater then the previous random number every time the code reruns. For example when the code runs first time it returns 1000 and then when it runs second time it returns 1300.
Conditions: The number must always be an integer.
function randomFunction() {
var x = 0
return function() {
x = x + Math.round( Math.random() * 100 )
return x
}
}
var nextRandom = randomFunction()
nextRandom() // => 51
nextRandom() // => 127
nextRandom() // => 203
How about this?
function myRnd(prev, max) {
return prev + Math.floor(Math.random() * max) + 1;
}
var last;
last = myRnd(1000, 500);
last = myRnd(last, 500);
EDIT
Being inspired by #dimakura's outstanding answer, here is my closure-based function which accepts start value and next max random step:
function myRndFunc(baseValue) {
return function(max) {
baseValue += Math.floor(Math.random() * max) + 1;
return baseValue;
};
}
var myRnd = myRndFunc(1000);
myRnd(300);
myRnd(500);
How about simply adding the previous number?
Try this :
for (i = 0; i < n; i++) {
newR = Math.floor((Math.random() * 1000) + oldR);
// use newR here.
oldR = newR;
}
Conbine Math.random() with Math.floor() setting the minimum end of your range to the last result.
var min = 0;
var max = 10000;
$("#randomise").click(function() {
var result = Math.floor(Math.random() * (max - min)) + min;
$("#result").text(result);
min = result;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
<button id="randomise">Randomise</button>
I need a javascript where with every second call i get a random number between 0-100 where current number should be greater than previous number. I wrote a code to get random numbers every second but stuck at generating it with increment.
<script>
var span = document.getElementsByTagName("span")[3];
var i = 100;
(function randNumber() {
var a = Math.floor((Math.random() * i) + 1);
span.innerHTML = "RandNumber: " + a;
setTimeout( randNumber, 1000);
})();
Note : The numbers should generate randomly.
example result may be : 2,5,7,8,22,23,34,56,78,88.....
You should not create a new random number between zero and your maximum (i), but just between the last created number (lastNumber) and max (i).
Also you might want to stop, when the random numbers reached the maximum.
var span = document.getElementsByTagName("span")[3],
i = 100,
lastNumber = 0;
function randNumber() {
lastNumber = lastNumber + Math.floor( Math.random() * (i - lastNumber) + 1 );
span.innerHTML = lastNumber;
if( lastNumber < i ) {
setTimeout( randNumber, 1000 );
}
}
randNumber();
AS for the comments and the requirement of a minimum amount of steps until reaching the maximum:
In each iteration, just increase you number by a random value between 1 and ((max - min) / steps. It is pretty much the same code as above.
var span = document.getElementsByTagName("span")[3],
max = 100,
min = 0,
lastNumber = 0,
minSteps = 30;
// how wide can the average step be at most?
var stepWidth = (max - min) / minSteps;
function randNumber() {
lastNumber = lastNumber + Math.floor( Math.random() * stepWidth + 1 );
span.innerHTML = lastNumber;
if( lastNumber < max ) {
setTimeout( randNumber, 1000 );
}
}
randNumber();
If you extract the "between two numbers" logic into its own function like this, this becomes a lot easier. This way, you just generate a number between your last generated number and your maximum.
var max = 100
var last_number = 1
var interval_id = setInterval(function(){
last_number = get_random_number_greater_between(last_number, max)
span.innerHTML = "RandNumber: " + last_number;
if(last_number >= max){
window.clearInterval(interval_id)
}
}, 1000)
function get_random_number_greater_between(low, high){
return Math.floor(Math.random() * (high - low + 1) + low);
}
Try this:
// generate a random number from 0 to max - 1.
function rand(max) {
return Math.floor(max * Math.random());
}
// generate a random number from min to max.
function range(min, max) {
return min + rand(1 + max - min);
}
// the loop function
function next(n, callback) {
var m = range(n, 100);
if (m < 100) setTimeout(next, 1000, m + 1, callback);
callback(m);
}
var span = document.getElementById("rand");
next(0, function (m) {
span.innerHTML = "Random number: " + m;
});
<span id="rand"></span>
How can I decrease the value of a variable by 0.2 every 5 minutes?
I have a variable var = 7.2. Now I added a button so when I click on it the variable will increment by 1.
Now I want to add an option where the variable decrement by 0.2 every 5 minutes and stop at the original number 7.2.
I have already tried window.setInterval() without successs.
Try this.
function myFunction(){
if (counter === 0){
document.getElementById("dicht").src = "images/open.jpg";
degree = degree + 0.9;
temp.innerHTML = degree; //+ " " + "graden celsius in de wijnkoeler";
counter = 1;
} else if (counter === 1){
document.getElementById("dicht").src = "images/dicht.jpg";
var id = window.setInterval(function(){
degree = parseFloat(Math.max(7.2, (degree - 0.2)).toPrecision(2));
if(degree == 7.2){
window.clearInterval(id);
counter = 0;
}
temp.innerHTML = degree;
}, 1000 * 60 * 5);
}
}
Here is how to use setInterval
var number;
var interval = setInterval(function(){
if (number < 7.2 ) clearInterval(interval);
number = number - 0.2;
}, 300000);
It's done by using setInterval
var time = 7.2;
var fivemin = 300000;
$('someid').text(time);
setInterval(function(){
time = time - 0.2;
$('someid').text(time);
}, fivemin);
WORKING DEMO
Don't use setInterval, use setTimeout instead:
window.myVar = 7.2;
var incrementVar = function() {
window.myVar += 1;
}
var decrementVar = function() {
window.myVar -= 0.2;
setTimeout(decrementVar, (5 * 60 * 1000));
}
setTimeout(decrementVar, (5 * 60 * 1000));
And for the button:
My Button
This should do it:
// global variable
var myGlobal = 8.2;
window.onload = function countback() {
window.setInterval(function cb() {
if (myGlobal >= 7.4) {
myGlobal = parseFloat(myGlobal - .2).toFixed(1);
}
}, 5 * 60 * 1000);
};
NOTE: If you are using a JS library like jQuery some of this can be done much more easily.
How to generate random duration value of second argument ( duration) in setInterval function.
//such as
var timerId = setInterval( timer_counter,getRandomInt(5,60),number,slatt);
var n = 10, // max value
r = Math.floor(Math.random() * n) + 1; // random number (1-10)
setInterval(function(){
timer_counter();
}, r * 1000); // to milliseconds
You're looking for Math.random() I believe (coupled with Math.floor).
Note: If r is (for example) 3, it will execute every 3 seconds for the life of that interval. If you want it to change, you need to use a setTimeout and change the timeout on every call. So to do that:
function worker(){
// the code that should be executed
}
function repeat(){
var n = 10; // every 1-10 seconds
setTimeout(function(){
worker();
repeat();
}, (Math.floor(Math.random() * n) + 1) * 1000);
}();
And to give you that getRandomInt function:
function getRandomInt(nMax, nMin){
nMax = nMax || 10;
nMin = nMin || 0;
return Math.floor(Math.random() * (nMax - nMin + 1)) + nMin;
}