Generate random numbers Jquery - javascript

I'd like to show a random numbers within my list. Im grabbing the list from the backend, and im just using these numbers as examples. This is my code, I'm not quite sure why its not filling in the text.
setInterval(function() {
var number = 1 + Math.floor(Math.random() * 6);
$('.num-gen').text(number);
},
Made a fiddle here to show you what I'm working with. Thanks in advance.

You had an error in your code, you were missing the finishing , 1000/*time in ms*/);!
Also, jQuery is not required here, you may do this in Javascript like this.
setInterval(function() {
var number = 1 + Math.floor(Math.random() * 6);
document.getElementsByClass('num-gen')[0].innerHtml = number;
}, 1000);
EDIT:
setInterval(function() {
jQuery.each(jQuery('.num-gen'),function(){
var number = 1 + Math.floor(Math.random() * 6);
jQuery(this).text(number);
});
}, 1000);

you have syntax error in you code, change it to:
setInterval(function() {
var number = 1 + Math.floor(Math.random() * 6);
$('.num-gen').text(number);
}, 10);

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;
...`

How to use if-statement with randgen [duplicate]

This question already has answers here:
Random number, which is not equal to the previous number
(16 answers)
Closed 4 years ago.
I'm trying to make sure two randomly generated numbers don't match, is there a way to do this in an if-statement?
i'm fairly new to javascript and couldn't find anything that answered my question, rand2 and rand3 both pick from the same list and it would make the outcome seem odd if they matched. my code also stopped working when i put the if-statement in (if i messed that up i guess it wouldn't matter if i got an answer).
function sentence() {
var rand1 = Math.floor(Math.random() * 2);
var rand2 = Math.floor(Math.random() * 12);
var rand3 = Math.floor(Math.random() * 12);
var rand4 = Math.floor(Math.random() * 10);
var rand5 = Math.floor(Math.random() * 10);
var rand6 = Math.floor(Math.random() * 10);
// var randCol = [rand1,rand2,rand3,rand4,rand5];
// var i = randGen();
if (rand2 == rand3) {
// whatever changes one
} else {
//
}
You could use a do while statement that runs while the numbers are the same, therefore will terminate as soon as the random numbers generated are different.
e.g.
var rand2 = 1;
var rand3 = 1;
do {
rand2 = Math.floor(Math.random() * 12);
rand3 = Math.floor(Math.random() * 12);
} while(rand2 === rand3 );
Hope that helps :)

Replace method with array value

I am using a random function to randomly slide between 4 swiper sliders, here is my code :
var swipers = [swiper1, swiper2, swiper3, swiper4];
setInterval(function(){
var rand = Math.floor(Math.random() * 4);
swipers[rand].slideNext();
}, 3000);
}
How should i proceed if i wanted to randomize between slideNext() and slidePrev() ? I tried many things like this :
var direction = ['slideNext()', 'slidePrev()'];
var swipers = [swiper1, swiper2, swiper3, swiper4];
setInterval(function(){
var randx = Math.floor(Math.random() * 4);
var randy = Math.floor(Math.random() * 2);
swipers[randx].direction[randy];
}, 3000);
But it's not working, probably for obvious reasons, but please help me understand why it's not working. And how i could possibly achieve that?
Just put the method name in the arrays, without parentheses. Then use it to index the object, and call the result of that.
You should also use <arrayname>.length rather than hard-coding the lengths when you get the random index, so you don't have to change it if you add more swipers or directions.
var direction = ['slideNext', 'slidePrev'];
var swipers = [swiper1, swiper2, swiper3, swiper4];
setInterval(function(){
var randx = Math.floor(Math.random() * swipers.length);
var randy = Math.floor(Math.random() * direction.length);
swipers[randx][direction[randy]]();
}, 3000);
You're pretty close! Just change how you're setting the direction and I think you got it:
swipers[randx][direction[randy]]();
Also remove the parenthesis from your array and just leave the function names there.

Create countdown in rowview (Titanium)

I am a beginner in Appcelerator Titanium APP development. From the inspiration of this link I am trying to create a countdown timer to be work in TableRowView as each row have its own time set. And I customize this class to show Hours with minutes and seconds.
I created the following code in each TableRowView to execute countdown in list on the fly.
Code 1
my_timer[timer_index] = new countDown(parseInt(timer_index), parseInt(15), parseInt(50),
function() {
remainingTime.text = ''+my_timer[timer_index].time.h + " : " + my_timer[timer_index].time.m + " : " + my_timer [timer_index].time.s;
}, function() {
//alert("The time is up!");
}
);
my_timer[timer_index++].start();
my_time used to push all the instances of countdown timer for each row.
The data is coming from XHR, therefore I created an array literal to hold all instances like in the snippet of code.
Problem: when I try to run my app with this code, it shows me an exception saying something like "time.h is undefined". However, I defined time.h as you can see in code.
Furthermore, I can use this class for multiple countdowns by using single array
for example:
my_timer[0] = new countDown(2,5,5,function(){
somelabel1.text = my_timer[0].time.h+":"+my_timer[0].time.m+":"+my_timer[0].time.s;
})
my_timer[1] = new countDown(2,5,5,function(){
somelabel1.text = my_timer[1].time.h+":"+my_timer[1].time.m+":"+my_timer[1].time.s;
})
the above code works perfectly and it has no error. But if I try to use this class in loop and pass index number rather than hard-coded values like in Code 1, it shows exception as I stated above.
Any help will be highly appreciable.
Thank you in advance.
Well, if I had to guess, which I do have to guess because you didn't give us a complete example or even a description of your problem...
Gut instinct is you're looping through to create the rows, referencing a mutable variable (remainingTime) as you do so in a nested function. But when you move on to the next item in the loop, remainingTime changes. So when the nested function references it, it's not the same as what you originally specified, so only the last timer is updating.
This is demonstrated by the following code, which alerts "3" three times.
for (var i = 0; i < 3; i++) {
setTimeout(function() {
alert(i);
}, 100);
}
If you don't know why, or how to fix it, then I suggest you spend some more time cuddled up by a fire with a cup of joe and a good book on JavaScript.
THank you for your time and answers. I just solved this problem by customizing CountDown Class
var countDown = function(h, m, s, _instance_index, fn_tick, fn_end) {
return {
total_sec : h * 60 * 60 + m * 60 + s,
timer : this.timer,
instance_index : _instance_index,
set : function(h, m, s) {
this.total_sec = parseInt(heart) * 60 * 60 + parseInt(e) * 60 + parseInt(s);
this.time = {
h : h,
m : m,
s : s
};
return this;
},
start : function() {
var self = this;
this.timer = setInterval(function() {
///alert('running');
if (self.total_sec) {
self.total_sec--;
var hour = parseInt(self.total_sec / (60 * 60));
var min = (self.total_sec - (parseInt(hour * (60 * 60))) - (self.total_sec % 60)) / 60;
self.time = {
h : parseInt(self.total_sec / (60 * 60)),
m : parseInt(min),
s : (self.total_sec % 60)
};
fn_tick(self.time.h + ":" + self.time.m + ":" + self.time.s, self.instance_index);
} else {
self.stop();
fn_end();
}
}, 1000);
return this;
},
stop : function() {
clearInterval(this.timer);
this.time = {
h : 0,
m : 0,
s : 0
};
this.total_sec = 0;
return this;
}
};
};
And call this class by using the following code:
my_timer[items_json.Record.NEW[i].ASSIGN_QUEST_ID] = new countDown(parseInt(n[0]), parseInt(n[1]), parseInt(n[2]), items_json.Record.NEW[i].ASSIGN_QUEST_ID, function(curr_time, instance_index) {
questTime[instance_index].text = 'TIME LEFT ' + curr_time;
}, function() {
//alert("The time is up!");
});
my_timer[items_json.Record.NEW[i].ASSIGN_QUEST_ID].start();

Remember last n items in jQuery

I have some code to randomly highlight one name from a list (this works - see this fiddle):
function pickRandom() {
var random = Math.floor(Math.random() * 6);
$('.stname').css('background','none').eq(random).css('background','yellow');
}
But I'd like to make sure that the same names don't come up over and over. So I intend to remember the last 3 chosen indexes as a blacklist:
var recentlyAsked = new Array();
function pickRandom() {
var random;
do {
random = Math.floor(Math.random() * 6);
} while ($.inArray(random,recentlyAsked));
recentlyAsked.push(random);
if (recentlyAsked.length >= 4) recentlyAsked.shift();
$('.stname').css('background','none').eq(random).css('background','yellow');
}
This is not working; see this fiddle. Warning: it causes the browser to hang.
Any suggestions, please?
do {
random = Math.floor(Math.random() * 6);
} while ($.inArray(random,recentlyAsked));
Runs forever because inArray returns -1 when an item is not found in the array, which is a truthy value. 0 is the only number that is a falsy value. Your array is initially empty so nothing is found.
Fix it with :
do {
random = Math.floor(Math.random() * 6);
} while ($.inArray(random,recentlyAsked) > -1);
This will stop when it returns -1(not found)
var ids=['a','b','c'];
var old=['d','e','f'];//At the beginning this will need populated with 3 random values
var ran=Math.floor(Math.random() * ids.length);
var ele=ids.splice(ran,1);
old.push(ele);
ids.push(old.shift());
highlight(ele);
Here is a slightly alternative way to do what you want. The idea is just remove chosen elements and then add it back in to the original array.
Just thought I would throw my code out there:
var randomArray = new Array(0, 1, 2, 3, 4, 5);
var pastArray = new Array();
function pickRandom() {
var random = Math.floor(Math.random() * randomArray.length);
$('.stname').css('background', 'none').eq(randomArray[random]).css('background', 'yellow');
if (pastArray.length < 3) {
pastArray.unshift(randomArray[random]);
randomArray.splice(random, 1);
} else {
pastArray.unshift(randomArray[random]);
randomArray.splice(random, 1, pastArray.pop());
}
console.log("possible values: [" + randomArray + "]");
console.log("past values: [" + pastArray + "]");
}
Values are moved back and forth from the current and past values. There is no need to prepopulate values as 'past', so it starts out truly random.

Categories

Resources