JavaScript Loop Animation Interval - javascript

I'm trying to get this loop to return a value, for each value in an array every 1 second.
The returned value is a random value generated earlier, and each loop will add i to the number and output it. (ran[0]+i) (ran[1]+i) etc.
I need the output in the same order as my example, but with a 1 second interval and something to generate my returns/consolelogs instead of having to type in all 4, or however many I use (could be random).
The code is for an animation but I cannot get the SVG working here and its irrelevant to the problem I think.
var ran = [];
var qan = 4;
for(i=0;i<(qan);i++){
rd = Math.floor(Math.random()*360);
ran.push(rd);
};
for(i=0;i<10;i++){
/*need to have (random.length) number of console logs and interval loops by 1 second*/
console.log((ran[0]+i) + " loop " + (i));
console.log((ran[1]+i) + " loop " + (i));
console.log((ran[2]+i) + " loop " + (i));
console.log((ran[3]+i) + " loop " + (i));
};

You may do like this;
var ran = [];
var qan = 4;
for(let i=0;i<(qan);i++){
rd = Math.floor(Math.random()*360);
ran.push(rd);
setTimeout(function(){console.log(ran[i])},1000*i);
}
Or by using var instead of let you can still do like this by utilizing an IIFE to return a callback with an encapsulated i value.
var ran = [];
var qan = 4;
for(var i=0;i<(qan);i++){
rd = Math.floor(Math.random()*360);
ran.push(rd);
setTimeout((function(j){ return function(){ console.log(ran[j]) } })(i),1000*i);
}
Update: I hope i am getting closer.. I just console.log the array itself but the items increase by i in each round. (10 rounds / frames)
var randar = new Array(4).fill().map(e => ~~(Math.random()*360));
console.log("starting random array ",randar); // let's see how the random array starts
for (let i = 0; i < 10; i++){
setTimeout(function(){console.log(randar.map(e=> e+i))} ,1000*i);
}
Note: I use arrows mostly but if you have concerns about IE or Safari then it's best to replace them with conventional function calls.

Related

I would like to know how I can make the "namePrinter" loop function work well?

I was trying to get javascript to print the result of the "generateName" function at least 10 times when I press a button in the html, so i tried a loop inside the function that generates the names and but it didn't work then I separated the loop and wrote it in the function "namePrinter" and create the global variable "names" to store the results of the function "generateName"
but I don't know what part of this whole process is wrong, I already reviewed other questions that were made in this forum but I didn't find an answer either
JS:
//this run the funtion that prints the names
document.getElementById("elvenFemButton").onclick = namePrinter;
//cutting characters function
function capFirst(string){
return string.charAt(10).toUpperCase() + string.slice(1);
}
//Randomizer
function getRandomInt (min,max){
return Math.floor(Math.random() * (max-min)) + min;
}
//this function generates names using both "elfFemName" and "elfLastName" and the functions from above
function generateName(){
var elfFemName1 = ["Adaia","Alisaie","Allisara","Alengwan","Alglaranna","Alachia","Alysia","Amberle","Anethra","Anwen","Apolline","Arathel","Ariane","Arianni","Ariel","Arwen","Ashalle","Ashniel","Atara","Ayara","Brelyna","Briala","Celebrían","Clothild","Cullich","Cylia","Dalish","Dirael","Eldyra","Elanor","Elenwen","Elezen","Ellia","Elynea","Éowyn","Failla","Faralda","Fleur","Freyalise","Galadriel","Gheyna","Jenassa","Katriel","Kira","Laina","Laniatte","Lauriel","Liallan","Liriel","Liselle","Loriel","Lorian","Lúthien","Máire","Mayael","Merril","Miara","Mihris","Minaeve","Nadja","Niranye","Nirya","Raewyn","Selveni","Sera","Shaera","Siofra","Taarie","Tauriel","Valora","Valya","Vanadis","Vanora","Velanna","Ylthin","Ysayle","Yvraine","Zelda"];
var elfLastName2 = ["Aearonian"," Agaraen","Agarher","Agarvran","Aire","Airendil","Amamion","Amdirthor","Amathal","Amather","Amathuilos","Amatheldir ","Amlugol","Aessereg","Aupwe","Calear","Caranagar","Cemno","Duindaer","Duirro","Eilianther","Gaer","Galadher","Gollor","Gulduron","Guldur","Guldurion","Hithaerben","Holiilo","Ingolmondur","Lar","Leucandil","Lanthir","Loeg","Lo","Lumorndaer","Morguldir","Morgulon","Naur","Neithaor","Nullion","Olchanar","Othanar","Olerydon","Ranchon","Rimdor","Rodor","Roher","Rhovanion","Rhovanion","Ruina","Russarocco","Sir","Sirdhemion","Tawaren","Tawarenion","Tawarher","Tordil","Uirchanar","Urendur","Urucher","Yr"];
var elfFemNameGenerator = capFirst(elfFemName1[getRandomInt(0, elfFemName1.length + 2)]) + " " + capFirst(elfLastName2[getRandomInt(0,elfLastName2.length +2)]);
return elfFemNameGenerator;
}
//i want this to get the result's from "generateName" and it should be a global value so i can use it in the next function
var names = generateName();
// this should print the name at least ten times but no
function namePrinter(){
var text = document.getElementById("textArea");
for (var i = 0; i < 10; i++) {
text[i].innerHTML(`${names}`)
}
return namePrinter;
}
innerHTML is not a function, it's a property. So, in the loop use text.innerHTML += name
However, if it's a <textarea> element, then you need to use value property instead:
//this run the funtion that prints the names
document.getElementById("elvenFemButton").onclick = namePrinter;
document.getElementById("elvenFemButton2").onclick = namePrinter2;
//cutting characters function
function capFirst(string){
return string.charAt(10).toUpperCase() + string.slice(1);
}
//Randomizer
function getRandomInt (min,max){
return Math.floor(Math.random() * (max-min)) + min;
}
//this function generates names using both "elfFemName" and "elfLastName" and the functions from above
function generateName(){
var elfFemName1 = ["Adaia","Alisaie","Allisara","Alengwan","Alglaranna","Alachia","Alysia","Amberle","Anethra","Anwen","Apolline","Arathel","Ariane","Arianni","Ariel","Arwen","Ashalle","Ashniel","Atara","Ayara","Brelyna","Briala","Celebrían","Clothild","Cullich","Cylia","Dalish","Dirael","Eldyra","Elanor","Elenwen","Elezen","Ellia","Elynea","Éowyn","Failla","Faralda","Fleur","Freyalise","Galadriel","Gheyna","Jenassa","Katriel","Kira","Laina","Laniatte","Lauriel","Liallan","Liriel","Liselle","Loriel","Lorian","Lúthien","Máire","Mayael","Merril","Miara","Mihris","Minaeve","Nadja","Niranye","Nirya","Raewyn","Selveni","Sera","Shaera","Siofra","Taarie","Tauriel","Valora","Valya","Vanadis","Vanora","Velanna","Ylthin","Ysayle","Yvraine","Zelda"];
var elfLastName2 = ["Aearonian"," Agaraen","Agarher","Agarvran","Aire","Airendil","Amamion","Amdirthor","Amathal","Amather","Amathuilos","Amatheldir ","Amlugol","Aessereg","Aupwe","Calear","Caranagar","Cemno","Duindaer","Duirro","Eilianther","Gaer","Galadher","Gollor","Gulduron","Guldur","Guldurion","Hithaerben","Holiilo","Ingolmondur","Lar","Leucandil","Lanthir","Loeg","Lo","Lumorndaer","Morguldir","Morgulon","Naur","Neithaor","Nullion","Olchanar","Othanar","Olerydon","Ranchon","Rimdor","Rodor","Roher","Rhovanion","Rhovanion","Ruina","Russarocco","Sir","Sirdhemion","Tawaren","Tawarenion","Tawarher","Tordil","Uirchanar","Urendur","Urucher","Yr"];
var elfFemNameGenerator = capFirst(elfFemName1[getRandomInt(0, elfFemName1.length)]) + " " + capFirst(elfLastName2[getRandomInt(0,elfLastName2.length)]);
return elfFemNameGenerator;
}
//i want this to get the result's from "generateName" and it should be a global value so i can use it in the next function
var names = generateName();
var names2 = [];
// this should print the name at least ten times but no
function namePrinter(){
var text = document.getElementById("textArea");
text.value = ""; //clear previous result
for (var i = 0; i < 10; i++) {
text.value += names;
}
}
function namePrinter2(){
var text = document.getElementById("textArea");
names2.length = 0; //clear array
for (var i = 0; i < 10; i++) {
names2[names2.length] = generateName();
}
text.value = names2;
}
<textarea id="textArea"></textarea>
<button id="elvenFemButton">generate names</button>
<button id="elvenFemButton2">generate different names</button>
This however as you can see will print the same name 10 times, if you need generate 10 names and store them globally, than you'll need save them in the array instead.
P.S.
Unrelated, but elfLastName2[getRandomInt(0,elfLastName2.length +2)] is wrong, you can't get value from an index that is larger than length of the array (aka +2 is wrong)

Why is my code causing (EDIT:) my page to crash?

I'm trying to randomly load some images to the page's html divs and my code is sometimes working, like on the first page load, but on maybe the second or third it causes the page to blank out and buffer and crashes the tab.
Here's a link to the full file (Excluding image srcs):
Here's the full js file: (be careful because it will crash the tab if you reload it several times)
https://repl.it/GBvG/2
var topnum = 7; //will later be used to represent current index
var rando; //will later be used as a swap index
var temporary; //will later be used as a temporary holder so we can swap rando and topnum
var myCard = document.getElementsByClassName('card');
var myArray = [
'Images/aceheart.png',
'Images/aceheart.png',
'Images/kingheart.png',
'Images/kingheart.png',
'Images/queenheart.png',
'Images/queenheart.png',
'Images/tenheart.png',
'Images/tenheart.png'
];
function create(){
while(topnum > 0){ //loops over all 8 elements
rando = Math.floor((Math.random() * topnum) + 0);
//will swap elements as long as the random index we got is not the same as the current index
if(myArray[rando] !== myArray[topnum]){
temporary = myArray[topnum];
myArray[topnum] = myArray[rando]; //randomizes topindex value
myArray[rando] = temporary;
topnum--;
}; // end of if
}; //end of while
for(var i = 0; i <= 8;i++){
var imgElement = "<img src='" + myArray[i] + "' alt='test' width='200px' height='275px'/>";
myCard[i].innerHTML = imgElement;
}; //end of for loop
}; // end of create
I'm almost positive the problem is with this snippet, though I don't know why:
for(var i = 0; i <= 8;i++){
var imgElement = "<img src='" + myArray[i] + "' alt='test' width='200px' height='275px'/>";
myCard[i].innerHTML = imgElement;
}; //end of for loop
You have 8 cards but your loop runs 9 iterations.
Change
for(var i = 0; i <= 8;i++)
To
for(var i = 0; i < 8;i++) // use `<` instead of `<=`
Also, as Gerardo Furtado mentioned in the comments, you should put topnum-- outside the if in the while loop. Otherwise you'll have an infinite loop.
while(topnum > 0) {
rando = Math.floor((Math.random() * topnum) + 0);
if(myArray[rando] !== myArray[topnum]){
// ...
}
topnum--; // <-- move the decrement here
}

Getting same result from function every time

why is my function returning the same result?
I would like to input all the values from the “ping” function to an array and then output that array in html.
I run the function 3 times but all three times the result is the same. Can you tell me why?
(The domains are just an example by the way, cant put originals here)
var str = ' ';
var t=[];
var n= 2;
var arr = ["www.google.com","www.example.com","www.example2.com"];
var results = [];
var finalurl = '';
function fun1(){
for (var i=0; i < arr.length; i++){
str = "http://" + arr[i] + "/images/";
finalurl = str + "image-l.gif" + "?id=" + (new Date()).getTime();
ping(finalurl);
textt += results[i] + " ";
$(‘#ping’).html(textt);
}
}
var ping = function(finalurl) {
var l = 0;
t.push((new Date()).getTime());
if(t.length > n) {
p=t[2]-t[1];
results.push(p);
}
else {
var img = new Image;
$(img).load(function() {
ping();
}).attr('src', finalurl);
}
}
//small part of html:
<h2>run</h2>
<h1 id=“ping”> </h1>
This generates three urls (the length of arr) but only attempts to show two (the value of n). The urls are different each time, but you are limiting them in ping so the new ones are not used.
Try setting n to higher number, you will see it will load more images each click - as it currently stands it tries to load more in a single click (3) than it allows (2).
Note: even if those urls are different, the images may be the same, this happens if the server ignores the id parameter... which probably does as it requires additional configuration for the server to handle requests to a ".gif" resource (which is not a known servcer side scripting language) - by default the server will just return the resource image-l.gif.
By the way: At $(‘#ping’) those are the wrong quotes. Also textt is not defined - I did define it as var textt = ''; for my tests.

javascript storing array values

Im trying to get the total combined value of a set of numbers.
Im getting the numbers as the text in an element tag storing them in an array then adding them all together. My problem is that its not inserting the numbers into the array as pairs.. it adding them as single integers .what am doing wrong.
check the jsfiddle too see example
http://jsfiddle.net/Wd78j/
var z = $('.impressions').text();
var x = [];
for(var i = 0; i < z.length; i++){
x.push(parseInt(z[i]));
}
console.log(x);
var total = 0;
$.each(x,function() {
total += this;
});
$('#impressTotals').append("[Total:" +total + "]");
$('#array').append("[Array:"+x+"]");
When you get text, it's taking all the numbers and concatenating them into a string. The below takes each element one at a time and pushes it.
var x = [];
$('.impressions').each( function( ) {
var z = $(this).text();
x.push(parseInt(z, 10));
})
Of course, you could build the sum up inside that each function, but I did it like this to more closely mirror your code.
text() returns the concatenated text of all of your impressions elements, of which you're adding together each character.
You want to loop through each impressions element, and keep a running sum going. Something like this should work
var sum = 0;
$('.impressions').each(function(){
sum = sum + (+$(this).text());
});
Updated Fiddle
Or to keep your original structure (don't forget the radix parameter to parseInt):
var z = $('.impressions');
var x = [];
z.each(function(){
x.push(parseInt($(this).text(), 10));
});
console.log(x);
var total = 0;
$.each(x,function() {
total += this;
});
$('#impressTotals').append("[Total:" +total + "]");
$('#array').append("[Array:"+x+"]");
Updated fiddle
You are iterating over a string, you could just use $.map to build the array instead, if you need it, otherwise just iterate and sum up the values :
var x = $.map($('.impressions'), function(el,i) {return parseInt($(el).text(), 10);}),
total = 0,
n = x.length;
while(n--) total += x[n] || 0;
$('#impressTotals').append("[Total:" +total + "]");
$('#array').append("[Array:"+x+"]");
FIDDLE

(P)RNG - Array of Random Numbers Created with a Seed

I want to create an array of random/pseudo-random numbers using a seed. I want the very same array to be created when the same seed is used and I want to have little or no visible pattern in the array. I'm working in JavaScript.
This is the random function I'm using, which I'm quite happy with (sorry, I forgot who the original author is):
function random(seed) {
if (!seed) seed = new Date().getTime();
seed = (seed*9301+49297) % 233280;
return seed/(233280.0);
}
This is the array generation:
var superSeed = random();
var nRandom = 100;
var randomArray = new Array();
for (var i = 0 ; i < nRandom ; i++){
randomArray.push(random((superSeed*10)+ (i)));
}
Somehow the pattern seems to be quite similar, no matter how often I run it. This question seems to be similar, but since it's about matrixes, I don't understand what's being said.
Thanks!
Having worked on similar things before I think we can use a fairly simple series, which takes two initial values and then you can get a lot more.
var a1,b1;
function InitSequence(v1, v2) {
a1 = Math.pow(v1, 5) / Math.pow(v1, 3);
b1 = Math.pow(v2, 8);
lastrand = (a1 + b1) & 0x7fffffff;
}
function SequenceNext() {
var alast = a1;
var nextVal = (a1 + b1) & 0x7fffffff;
b1 = alast;
a1 = nextVal;
return nextVal;
}
Then use it like this:
InitSequence(75, 21);
for (var i = 0; i < 99; i++) {
v = SequenceNext();
}
I tested it like this:
var used = new Array();
InitSequence(75, 21); // any two values will do.
// fill 10k into array.
for (var i = 0; i < 9999; i++) {
v = SequenceNext();
if (undefined != used[v]) {
used[v]++;
} else used[v] = 1;
//document.write(i+": "+v+"<br>");
}
// see if there any duplicates.
var tdup = 0;
for (xx in used) {
ndup = used[xx];
if (ndup > 1) {
document.write("duplicated " + xx + " :" + ndup + "<br>");
tdup += ndup;
}
}
document.write("Total dups " + tdup + "<br>");
This is using the Fibonacci series, which in mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation
. I'm starting with different values - (v1^5) / (v1^3) and v2 ^ 8; otherwise it would only ever be identical.
I like the "Super 7" PRNG. It is simple, fast (although the other answer with the fib. sequence is fast as well), and has the interesting property:
In the entire range -- albeit of a meager of 32k -- there are no duplicates using the "Super 7" PRNG.
Multiple 7's can be joined to increase the number of bits and/or provide multiple seeds. This non-duplication property can exposed or folded.
(The sequence of a PRNG is always the same given a starting seed: it's the distribution and cycle lengths that are interesting -- it is these properties that may make them ideal in different cases where "true randomness" isn't desired).
Happy coding.
Maybe you should try this
function s_random() {
s_random.m = 71402523; s_random.a = 409647; s_random.c = 1508892;
s_random.seed = (s_random.seed*s_random.a + s_random.c) % s_random.m;
return s_random.seed / s_random.m;
}
/*
generate IV
s_random.seed = Math.floor((new Date).getTime()/10000);
*/
s_random.seed = 130324232;
var CheckRandom = 4999999;
var PrintSamples = 100;
var used = new Array();
for (var i = 0; i < CheckRandom; i++) {
v = (Math.ceil(Math.sqrt(s_random())* 1000000000) * 8);
if (undefined != used[v]) {
used[v]++;
} else used[v] = 1;
if ( i< PrintSamples) document.write(i+": "+v+"");
}
/* see if there are any duplicates. */
var tdup = 0;
for (xx in used) {
ndup = used[xx];
if (ndup > 1) {
if (ndup < PrintSamples) document.write("duplicated " + xx + " :" + ndup + "");
tdup += ndup;
}
}
document.write("Total generated " + CheckRandom + "");
document.write("Total duplicates " + tdup + "");
Just got 5 million seeded, repeatable random numbers and no duplicates. Tested several times on Mac OS X with Safari.
Cheers,
Karl

Categories

Resources