Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I am creating just a little test game type thing, and for part of it, I need a function to be randomly selected.
I have 2 altogether, and I just need to create maybe a 'random generator' somehow, which I can call, and it runs one of the 2 functions.
function function1() {
........code.........
}
function function2() {
........code.........
}
function generator() {
...random function selector...
}
Maybe something like that ^
Thanks in advance!
Yes, you can do that.
var myFuncArr = ["function1","function2"];
function generator(){
window[myFuncArr[Math.random() * (myFuncArr.length - 0) + 0]]();
}
JavaScript has an eval function that evaluates a string and executes it as code:
function generator(){
min = 1;
max = 5;
random = Math.floor(Math.random() * (max - min + 1)) + min;
param = "myParam";
eval("function"+random+"('"+param+"')");
}
Do you expecting like this
function method1(){
document.getElementById("sampleDiv").style.color = "red";
}
function method2(){
document.getElementById("sampleDiv").style.color = "yellow";
}
function method3(){
document.getElementById("sampleDiv").style.color = "orange";
}
function generator(id) {
eval("method"+id+"()")
}
function randomIntFromInterval(min,max)
{
return Math.floor(Math.random()*(max-min+1)+min);
}
setInterval(function(){generator(randomIntFromInterval(1,3))},3000);
Demo:
http://jsfiddle.net/hcmY9/3/
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I am trying to figure out how I can create a "game" where I have three dices, and three bets. If any of the bets hits, I will be granted 1 point, else nothing happens.
Example variables and arrays I would like to use;
var points = 1;
var slot1 = Math.floor((Math.random()*6)+1);
var slot2 = Math.floor((Math.random()*6)+1);
var slot3 = Math.floor((Math.random()*6)+1);
var dices = [slot1, slot2, slot3];
function Bet(bet1, bet2, bet3) {
"NEED HELP WITH THE CODE HERE"
}
Bet(1,2,3);
Thanks alot for all kinds of help!
I think a nudge in the right direction is more appropriate than a ready-to-go answer, since your question smells a little bit like homework :-)
You basically need to cross-check each item from both lists. You can do this with either a nested for .. in loop or a call to .some() with a nested .contains(). The latter will give you the cleanest solution. Docs
Alternatively, you can use Tagas' solution but that would make your function less reusable. If the number of bets vary, you'll need to adjust your function..
Try this:
function rollDice() {
//generate a number between 1 to 6
return Math.floor(Math.random() * (6 - 1 + 1)) + 1;
}
function makeBet(bet1, bet2, bet3) {
let slot1 = rollDice(),
slot2 = rollDice(),
slot3 = rollDice();
console.log('Slot 1:', slot1);
console.log('Slot 2:', slot2);
console.log('Slot 3:', slot3);
if(bet1 == slot1 || bet2 == slot2 || bet3 == slot3) {
//return 1 point as there is a match
return 1;
}
//return nothing as there was no match
return 0;
}
//Make a bet!
makeBet(1, 2, 3);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
How to write a function that returns a line from file with nodeJS? The program runs in the loop, and each time you call the function should return a new string. And if the file ends begins again, with the first line.
This function takes randomly, how to do consistently?
var fs = require('fs');
// Get random line from file
function getRandSocks() {
var socks = fs.readFileSync('socks.txt').toString().split("\n");
var randsock = socks[Math.floor(Math.random()*socks.length)];
return randsock.split(':');
}
function loop() {
// ...
var socks = getRandSocks();
console.log('host: '+socks[0]+'port :'+socks[1]);
//...
loop();
}
Perhaps this would help. This gets the next line and wraps back to the start. It is based on the given getRandSocks function with minimal change.
var current_line = 0;
function getNextLines() {
var socks = fs.readFileSync('socks.txt').toString().split("\n");
var randsock = socks[current_line % socks.length];
current_line = (current_line + 1) % socks.length
return randsock.split(':');
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
var x = document.getElementsByClassName("farm_icon_c");
for(var i=0;i<x.length;i++){
x[i].click();
setInterval(function () {}, 1000);
};
var w=frames.main||self, d=w.document, b=d.links[0].href.match(/(village=)(\d+)/);
w.location.href=w.location.href.replace(/&*village=[pnj]?\d+&*/g, '&').replace(/&+$/,"")+'&'+b[1]+'n'+b[2];
void(0);
see this script works but waaaaay too fast.. This interval function isnt working
I think you want something like
var x = document.getElementsByClassName("farm_icon_c"),
(function f(i) {
if(i < x.length) {
x[i].click();
setTimeout(function() { f(i+1); }, 1e3); // Run next "iteration" in 1 second
} else {
// This code will run at "the end of the loop"
}
})(0); // Run first "iteration" immediately
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
If I have these functions defined:
function playZoomout() {
// do things
}
function playZoomin() {
// do things
}
function playPanright() {
// do things
}
function playPanleft() {
// do things
}
and am running this every four seconds:
var timer = setInterval(playZoomout,4000);
How can I replace "playZoomout" with a randomly selected function picked from the ones defined above? I'm looking for a jQuery or plain javascript solution.
Create an array of function references, then fetch an element randomly from the array and invoke it.
var fns = [playZoomout, playZoomin, playPanright, playPanleft]
setInterval(function () {
fns[Math.floor(Math.random() * fns.length)]();
}, 1000)
Demo: Fiddle
Add each functionname to an array, with numerical key indexing. Then, randomly generate a number between the lower and upper index and use a control structure to repeat the process.
Something like this should work (see http://jsfiddle.net/w6sdc/):
/* A few functions */
var a = function() {
alert("A");
}
var b = function() {
alert("B");
}
var c = function() {
alert("C");
}
/* Add the functions to an array */
var funcs = [a, b, c];
/* Select a random array index */
var i = Math.floor(Math.random() * 2) + 0;
/* Call the function at that index */
funcs[i]();
Wrapping the index selection and the function call in a setInterval should be straight forward from this point.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I used this code but it's not repeat
it increase the value but don't get to the initial value 0
please help
i=0;
function loading()
{
text=["Loading.","Loading..","Loading...","Loading...."];
window.setInterval(wr(),500)
}
function wr()
{
if(i<4)
{
wr='document.getElementById("text").innerHTML=text[i]';
alert(i);
}
else
i=0;
return wr;
}
Your code is way to complicated. Define a simple function which you pass to setInterval and make sure you increase the counter variable:
var i = 0; // initialize counter
var textElement = document.getElementById("text");
setInterval(function() {
i = i % 4; // make sure `i` is at max 3 and reset to 0
var text = 'Loading';
for (var j = i; j--; ) {
text += '.'; // add the correct number of periods
}
textElement.innerHTML = text; // set text
i++; // increase counter
}, 500);
DEMO
Here's a slight modification of a similar answer I gave a while back.
var i = 0;
setInterval(function() {
i = ++i % 4;
document.getElementById('text').innerHTML = "Loading"+Array(i+1).join(".");
}, 500);