Unity javascript infinite spawning - javascript

So I'm trying to set up a system in a project where these spawn points will spawn targets that move towards the player and have to be destroyed before reaching a certain point, or its game over. Everything seems to be working fine except for one issue. The spawners don't stop spawning. They're supposed to do waves, spawning more enemies after each wave has been finished. I'm totally lost as to where the error might be.
Small note, originally I had the spawn count be 3 times the enemyspawncount, and spawnCount would count down to 0, then jump to 2 and remain there.
Spawner script:
var targetPrefab:Transform;
var spawnCount = deathcounter.enemySpawnCount;
function Start()
{
StartCoroutine("CoStart");
}
function CoStart() : IEnumerator
{
while (true)
yield CoUpdate();
}
function CoUpdate(){
spawnCount = deathcounter.enemySpawnCount;
while(spawnCount > 0)
{
var target= Instantiate(targetPrefab, transform.position, transform.rotation);
target.rigidbody.AddForce(Vector3.right * (deathcounter.enemySpawnCount *0.5 * 100));
spawnCount = spawnCount - 1;
Debug.Log("Spawn" + spawnCount);
yield WaitForSeconds (5);
}
deathcounter.timeToSpawn = false;
}
Target script:
var spawnCount = deathcounter.enemyDeathCount;
function OnTriggerEnter() {
Destroy (gameObject);
deathcounter.enemyDeathCount = deathcounter.enemyDeathCount + 1;
}
Death Counter script:
static var enemyDeathCount = 0;
static var enemySpawnCount = 1;
static var timeToSpawn : boolean = true;
function Update () {
if(enemyDeathCount % 3 == 0 && enemyDeathCount != 0){
timeToSpawn = true;
enemySpawnCount = enemySpawnCount + 1;
}
}

The issue could be in function CoUpdate(). The value of deathcounter.enemySpawnCount never gets reduced in that function. So if CoUpdate() gets called again, deathcounter.enemySpawnCount will still have the same value, and more enemy prefabs will get instantiated.
If that is the issue, and I'm not just misreading your code, you can solve that easily by setting deathcounter.enemySpawnCount after you set spawnCount:
spawnCount = spawnCount - 1;
deathcounter.enemySpawnCount = spawnCount;
Debug.Log("Spawn" + spawnCount);
Debug.Log("Spawn (double-check) " + deathcounter.enemySpawnCount);

With much more mature eyes, I can look back and correct myself.
First I have to flip the order of these commands so they both trigger.
function OnTriggerEnter() {
deathcounter.enemyDeathCount = deathcounter.enemyDeathCount + 1;
Destroy (gameObject);
}
Second I have to redo how spawnCount is handled. It should be removed from the 'target' script, and given a set initial value, not set to another variable value. It should only be changed in the while loop with each iteration, and in the death counter script, inside the if statement, so it is set to be equal to the new enemySpawnCount value only when that if statement is true.

Related

pass a function with its values "locked"

Say I have a queue class that's executing a series of functions I've already declared:
class DrawQueue{
constructor(interval){
this.sequence = [];
this.interval=interval?interval:50;
}
addFunction=(fn)=>{
this.sequence.push(fn);
//throw exception here if not a function
};
execFunctions = ()=>{
let intvl = setInterval(
()=>{
const fn = this.sequence.shift();
//clear interval & return here if not a function
fn.call();
},
this.interval
)
}
}
Now I want to pass it a series of functions that have some values calculated inside them:
//I have a single count variable here but the code I'm running is being generated by a user who might have any number of variables that are being updated
let count = 0;
let counterDiv = document.querySelector('#counter')
let dq = new DrawQueue(1000);
function startCount(){ //call when window's loaded
let countFn=(()=>
{
let innerFn= function(){
let str = (function(){
return count.toString()
})();
counterDiv.innerHTML=str;
}
//imagine that any number of count variables might be being updated somewhere in the function
count++;
dq.addFunction(innerFn);
})
while(count<10){
countFn();
}
dq.execFunctions();
}
Right now this immediately sets the counter div to 10, and then keeps setting it to 10 ten more times. But I want to assign the str variable's value before I pass the functions. So the first function I pass sets the counter to 1, then 2 and so on.
I was trying to set the let str= function(... using an iife, but that didn't work.
One solution that I know would work is to make the whole function a string and then run it with eval but I really do not want to use eval unless I absolutely have to.
Is there any other way to pass these functions with certain variables already "locked in", meaning they're assigned before the function is placed in the queue?
UPDATE: To clarify, this is just a simplified version of a more complex example. In the actual example, the code is dynamically generated by another user, so in addition to 'count' any number of other values might need to be evaluated. So passing the count variable, as several good answers have suggested, is not going to work.
FURTHER CLARIFICATION: What I'm saying above is that because the user could be generating any number of variables that will be updated as the code runs, I can't pass those variables as arguments. (imagine there might be a count2, count3...countn and I don't know how many or where they'll be used or updated in the code.
FURTHER UPDATE: so a commenter wants to see the code in which this applies so here goes. It is an application using Blockly and P5 play, where users will be making code with blocks to move a sprite. So the code for the blocks might be something like this (yes this code is really ugly because it's just a test, but you asked to see it):
function moveForward(sprite){
let dir = ship.rotation* (Math.PI / 180);
let deltaX = Math.cos(dir)*5;
let deltaY = Math.sin(dir)*5;
let newX = ship.position.x + deltaX;
let newY = ship.position.y + deltaY;
ship.position.x=newX;
ship.position.y=newY;
redraw();
}
function moveBackward(sprite){
let dir = ship.rotation* (Math.PI / 180);
let deltaX = Math.cos(dir)*5;
let deltaY = Math.sin(dir)*5;
let newX = ship.position.x - deltaX;
let newY = ship.position.y - deltaY;
ship.position.x=newX;
ship.position.y=newY;
redraw();
}
function turnLeft(sprite){
let newDir=ship.rotation-90;
ship.rotation=newDir;
redraw();
}
function turnRight(sprite){
let newDir=ship.rotation+90;
ship.rotation=newDir;
redraw();
}
There will be any number of other sprites, each with 20 or so properties that could be updated.
Now if I just put all these functions in a row, the sprite will just immediately jump to where the code would put it. Because, you know, normally we want computers to do things as fast as they can.
But since this is made for teaching, I want the user to see the canvas updating step by step, with a delay between each redraw. That means every sprite will have its x and y coordinates, along with color and rotation and a bunch of other things, change slowly.
So the purpose of the DrawQueue to execute the drawing update steps slowly with a setInterval and update the canvas at any interval I want. I can't just run every single command with a setInterval because there could be logic or loops in there. The only thing I want to go in the interval is the updates to the canvas, anything else can happen as fast as it wants.
So imagine the four functions I provided above, along with any number of other functions and modifications to the properties of any number of other sprites or properties of the canvas.
The problem you have is the value is not stored at the time you make the function. It is just a reference to a variable that you are updating. So when it calls, it is reading that variable.
You would need to pass it into the method so you can store the state of the variable at that moment in time.
let count = 0;
let counterDiv = document.querySelector('#counter')
let dq = new DrawQueue(1000);
function startCount(){ //call when window's loaded
let countFn=((count)=> . // <-- reference it here
{
let innerFn= function(){
let str = (function(){
return count.toString()
})();
counterDiv.innerHTML=str;
}
dq.addFunction(innerFn);
})
while(count<10){
countFn(count++); // <-- update it here
}
dq.execFunctions();
}
By the time the innerFn is actually called, the count variable has already increased to its final value.
To give each innerFn instance its own value for count, you could bind it as function argument:
let innerFn = function(count) { //<--- argument
let str = (function(){
return count.toString()
})();
counterDiv.innerHTML=str;
}.bind(null, count); // pass the global count into a bound argument
NB: make sure to check in your class that fn is defined (as the array will become empty at some point).
class DrawQueue{
constructor(interval){
this.sequence = [];
this.interval=interval?interval:50;
}
addFunction(fn){
this.sequence.push(fn);
//throw exception here if not a function
};
execFunctions(){
let intvl = setInterval(
()=>{
const fn = this.sequence.shift();
//clear interval & return here if not a function
if (fn) fn.call();
},
this.interval
)
}
}
let count = 0;
let counterDiv = document.querySelector('#counter')
let dq = new DrawQueue(1000);
function startCount(){ //call when window's loaded
let countFn=(()=>
{
let innerFn= function(count){
let str = (function(){
return count.toString()
})();
counterDiv.innerHTML=str;
}.bind(null, count);
count++;
dq.addFunction(innerFn);
})
while(count<10){
countFn();
}
dq.execFunctions();
}
window.onload = startCount;
<div id="counter"></div>
Even better would be to avoid a reference to a global variable, and pass count to the countFn function as parameter:
let counterDiv = document.querySelector('#counter')
let dq = new DrawQueue(1000);
function startCount(){ //call when window's loaded
let countFn=((count)=> // local variable
{
let innerFn= function(){
let str = (function(){
return count.toString()
})();
counterDiv.innerHTML=str;
}
dq.addFunction(innerFn);
})
for(let count = 0; count<10; count++){ // local variable
countFn(count); // pass it
}
dq.execFunctions();
}
Addendum
In your question's update you speak of more variables. In that case, pass an object around, which can have many properties, possibly even managed completely by the user-provided code:
let counterDiv = document.querySelector('#counter')
let dq = new DrawQueue(1000);
function startCount(){ //call when window's loaded
let countFn=((state)=> // local variable with count property
{
let innerFn= function(){
let str = (function(){
return state.count.toString()
})();
counterDiv.innerHTML=str;
}
dq.addFunction(innerFn);
})
for(let count = 0; count<10; count++){ // local variable
const state = {};
state.count = count;
countFn(state); // pass it
}
dq.execFunctions();
}
Depending on your expectations you should either use the same state object or create new state variables (within the loop, or even deeper in the execution context). This all depends on how you want the system to behave.

HTML5 Canvas, Having Trouble Running Multiple Animations At Once

I have written code that takes two arrays, both of which contain co-ordinates for a four-cornered shape (effectively a start frame and an end frame), a canvas ID and a time value. The function then calculates dX and dY of each corner and uses window.performance.now() to create a timestamp. Then, on every requestAnimationFrame(), it calculates what the co-ordinates should be by using dX, dY, the old timestamp, a new timestamp and the time value from the function call. It looks like this:
function doAnim(cv, startFrame, endFrame, animTime)
{
this.canvas = document.getElementById(cv);
this.ctx = this.canvas.getContext('2d');
if(startFrame.length != endFrame.length)
{
return('Error: Keyframe arrays do not match in length');
};
this.animChange = new Array();
for(i=1;i<=startFrame.length;i++)
{
var a = startFrame[i];
var b = endFrame[i]
var c = b - a;
this.animChange[i] = c;
}
this.timerStart = window.performance.now();
function draw()
{
this.requestAnimationFrame(draw, cv);
this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height);
this.currentFrame = new Array();
for(i=1;i<=startFrame.length;i++)
{
this.currentFrame[i] = startFrame[i]+(this.animChange[i]*((window.performance.now()-this.timerStart)/animTime));
}
if((window.performance.now()-this.timerStart)>=animTime)
{
this.ctx.beginPath()
this.ctx.moveTo(endFrame[1], endFrame[2]);
this.ctx.lineTo(endFrame[3], endFrame[4]);
this.ctx.lineTo(endFrame[5], endFrame[6]);
this.ctx.lineTo(endFrame[7], endFrame[8]);
this.ctx.fill();
return;
}
else
{
this.ctx.beginPath()
this.ctx.moveTo(this.currentFrame[1], this.currentFrame[2]);
this.ctx.lineTo(this.currentFrame[3], this.currentFrame[4]);
this.ctx.lineTo(this.currentFrame[5], this.currentFrame[6]);
this.ctx.lineTo(this.currentFrame[7], this.currentFrame[8]);
this.ctx.fill();
}
}
draw();
}
The goal is to have multiple animations of objects happening at once. I took the whole co-ordinate approach because I want the objects to appear as if they are coming from the horizon, creating a fake 3D perspective effect (all objects' starting frames would be a single point at the center of the canvas), and I do not want to warp the objects' textures.
Well, it works great for a single animation, but if I try to start a new animation on a completely different canvas while the first one is running, then the first animation stops dead in its tracks.
As you can see from my JS, I've tried getting around this with gratuitous use of this (I do not fully understand how this works yet, and every explanation I've read has left me even more confused), but it has not worked. I also tried a horrific approach which stored all the functions' own variables in one global array (the first time the function runs, all the variables are put in entries 1-30, the second time they're put in 31-60, etc). Unsurprisingly, that did not work either.
Here is a JSFiddle so you can see this scenario for yourself and play with my code. I am officially out of ideas. Any help will be greatly appreciated.
Like markE linked too, trying to call requestAnimationFrame multiple times won't work.
Instead you make multiple objects and then call some sort of function on them each frame.
I have created an example using your code:
https://jsfiddle.net/samcarlin/2bxn1r79/7/
var anim0frame1 = new Array();
anim0frame1[1] = 0;
anim0frame1[2] = 0;
anim0frame1[3] = 50;
anim0frame1[4] = 0;
anim0frame1[5] = 50;
anim0frame1[6] = 150;
anim0frame1[7] = 0;
anim0frame1[8] = 150;
var anim0frame2 = new Array();
anim0frame2[1] = 200;
anim0frame2[2] = 200;
anim0frame2[3] = 300;
anim0frame2[4] = 250;
anim0frame2[5] = 300;
anim0frame2[6] = 300;
anim0frame2[7] = 200;
anim0frame2[8] = 250;
//Call global
animations = [];
requestAnimationFrame( GlobalStep );
function GlobalStep(delta){
//Functions called by request animation frame have the new time as an argument
//so delta should be approximately the same as window.performance.now()
//especially in realtime applications, which this is
//Check if we have any animation objects
if(animations.length > 0){
//Iterate through and call draw on all animations
for(var i=0; i<animations.length; i++){
if(animations[i].draw(delta)){
//Basically we have it so if the draw function returns true we stop animating the object
//And remove it from the array, so have the draw function return true when animation is complete
animations[i].splice(i, 0);
//We removed an object from the array, so we decrement i
i--;
}
}
}
//And of course call requestAnimationFrame
requestAnimationFrame( GlobalStep );
}
function AnimationObject(cv, startFrame, endFrame, animTime){
//Add this object to the objects arrays
animations.push(this);
//We need to store start and end frame
this.startFrame = startFrame;
this.endFrame = endFrame;
this.animTime = animTime;
//Your code
this.canvas = document.getElementById(cv);
this.ctx = this.canvas.getContext('2d');
if (startFrame.length != endFrame.length) {
return ('Error: Keyframe arrays do not match in length');
};
this.animChange = new Array();
for (i = 1; i <= startFrame.length; i++) {
var a = startFrame[i];
var b = endFrame[i]
var c = b - a;
this.animChange[i] = c;
}
this.timerStart = window.performance.now();
}
//This adds a function to an object, but in such a way that every object shares the same function
//Imagine a kitchen, each object is a person, and this function is a spoon
//by defining this function in this manner Object.prototype.function_name = function(arguments){}
//We make it so one function definition is needed, essentially allowing all the people to share one spoon,
//the 'this' variable still refers to whichever object we call this method, and we save memory etc.
AnimationObject.prototype.draw = function(newTime){
//I added this to start frame so we get what we stored earlier
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.currentFrame = new Array();
for (i = 1; i <= this.startFrame.length; i++) {
this.currentFrame[i] = this.startFrame[i] + (this.animChange[i] * ((newTime - this.timerStart) / this.animTime));
}
if ((newTime - this.timerStart) >= this.animTime) {
this.ctx.beginPath()
this.ctx.moveTo(this.endFrame[1], this.endFrame[2]);
this.ctx.lineTo(this.endFrame[3], this.endFrame[4]);
this.ctx.lineTo(this.endFrame[5], this.endFrame[6]);
this.ctx.lineTo(this.endFrame[7], this.endFrame[8]);
this.ctx.fill();
return;
} else {
this.ctx.beginPath()
this.ctx.moveTo(this.currentFrame[1], this.currentFrame[2]);
this.ctx.lineTo(this.currentFrame[3], this.currentFrame[4]);
this.ctx.lineTo(this.currentFrame[5], this.currentFrame[6]);
this.ctx.lineTo(this.currentFrame[7], this.currentFrame[8]);
this.ctx.fill();
}
}
Notes:
Everytime you press the button a new object is added and simply overwrites previous ones for each frame, you should implement your program so that it checks if a specific animation has already started, you could also use the builtin mechanism to stop animation when complete (read the comments in the code)
You also need to change the on button click code
<button onclick="new AnimationObject('canvas1', anim0frame1, anim0frame2, 3000);">
Lastly if you have further questions feel free to contact me

Understanding JavaScript setTimeout and setInterval

I need a bit of help understanding and learning how to control these functions to do what I intend for them to do
So basically I'm coming from a Java background and diving into JavaScript with a "Pong game" project. I have managed to get the game running with setInteval calling my main game loop every 20ms, so that's all ok. However I'm trying to implement a "countdown-to-begin-round" type of feature that basically makes a hidden div visible between rounds, sets it's innerHTML = "3" // then "2" then "1" then "GO!".
I initially attempted to do this by putting setTimeout in a 4-iteration for-loop (3,2,1,go) but always only displayed the last iteration. I tried tinkering for a bit but I keep coming back to the feeling that I'm missing a fundamental concept about how the control flows.
I'll post the relevant code from my program, and my question would be basically how is it that I'm writing my code wrong, and what do I need to know about setTimeout and setInterval to be able to fix it up to execute the way I intend it to. I'm interested in learning how to understand and master these calls, so although code examples would be awesome to help me understand and are obviously not unwelcome, but I just want to make it clear that I'm NOT looking for you to just "fix my code". Also, please no jQuery.
The whole program would be a big wall of code, so I'll try to keep it trimmed and relevant:
//this function is called from the html via onclick="initGame();"
function initGame(){
usrScore = 0;
compScore = 0;
isInPlay = true;
//in code not shown here, these objects all have tracking variables
//(xPos, yPos, upperBound, etc) to update the CSS
board = new Board("board");
ball = new Ball("ball");
lPaddle = new LPaddle("lPaddle");
rPaddle = new RPaddle("rPaddle");
renderRate = setInterval(function(){play();}, 20);
}
.
function initNewRound(){
/*
* a bunch of code to reset the pieces and their tracking variables(xPos, etc)
*/
//make my hidden div pop into visibility to display countdown (in center of board)
count = document.getElementById("countdown");
count.style.visibility = "visible";
//*****!!!! Here's my issue !!!!*****//
//somehow i ends up as -1 and that's what is displayed on screen
//nothing else gets displayed except -1
for(var i = 3; i >= 0; i--){
setInterval(function(){transition(i);}, 1000);
}
}
.
//takes initNewRound() for-loop var i and is intended to display 3, 2, 1, GO!
function transition(i){
count.innerHTML = (i === 0) ? "Go" : i;
}
.
//and lastly my main game loop "play()" just for context
function play(){
if(usrScore < 5 && compScore < 5){
isInPlay = true;
checkCollision();
moveBall();
moveRPaddle();
if(goalScored()){
isInPlay = false;
initNewRound();
}
}
}
Thanks a bunch for your advise, I'm pretty new to JavaScript so I really appreciate it.
Expanding on cookie monster's comment, when you use setInterval in a loop, you are queueing up method executions that will run after the base code flow has completed. Rather than queue up multiple setInterval executions, you can queue up a single execution and use a variable closure or global counter to track the current count. In the example below, I used a global variable:
var i = 3 // global counter;
var counterInterval = null; // this will be the id of the interval so we can stop it
function initNewRound() {
// do reset stuff
counterInterval = setInterval(function () { transition() }, 1000); // set interval returns a ID number
}
// we don't need to worry about passing i, because it is global
function transition() {
if (i > 0) {
count.innerHTML = i;
}
else if (i === 0) {
count.innerHTML = "Go!";
}
else {
i = 4; // set it to 4, so we can do i-- as one line
clearInterval(counterInterval); // this stops execution of the interval; we have to specify the id, so you don't kill the main game loop
}
i--;
}
Here is a Fiddle Demo
The problem is in this code:
for(var i = 3; i >= 0; i--){
setInterval(function(){transition(i);}, 1000);
}
When the code runs, it creates a new function 3 times, once for each loop, and then passes that function to setInterval. Each of these new functions refers to the variable i.
When the first new function runs it first looks for a local variable (in it's own scope) called i. When it does not find it, it looks in the enclosing scope, and finds i has the value -1.
In Javascript, variables are lexically scoped; an inner function may access the variables defined in the scope enclosing it. This concept is also known as "closure". This is probably the most confusing aspect of the language to learn, but is incredibly powerful once you understand it.
There is no need to resort to global variables, as you can keep i safely inside the enclosing scope:
function initNewRound(){
var i = 3;
var count = document.getElementById("countdown");
count.style.visibility = "visible";
var interval = setInterval(function(){
//this function can see variables declared by the function that created it
count.innerHTML = i || "Go"; //another good trick
i-=1;
i || clearInterval(interval); //stop the interval when i is 0
},1000);
}
Each call to this function will create a new i, count and interval.

Why is clearTimeout not working for this code?

I call the following code on mouse click:
clearTimeouts();
var inMotion = true, x = 0;
var shuffleTimer = setTimeout(function(){inMotion = false}, 3500);
var shuffleStart = setTimeout(oneShuffle, x);
function oneShuffle(){
x+=5;
if(inMotion === true){
console.log('Shuffling again');
//shuffle again
shuffleStart = setTimeout(oneShuffle, x);
} else {
//increment spins
spins++;
//reset spins if loadOrder been exhausted
spins === loadOrder.length ? spins = 0 : 0;
console.log(spins);
}
}
function clearTimeouts(){
console.log('Clearing timeouts')
clearTimeout(shuffleTimer);
clearTimeout(shuffleStart);
}
What should be happening is if I click the elment while inMotion is true the two timeouts should reset and my spins counter should not increase for the previous click. However, what happens instead is that spins gets incremented for the previous timeouts anyway. Why?
What timers should reset? If the code you posted is in a click handler, then each click produces new timers.
The lines:
var shuffleTimer = setTimeout(function(){inMotion = false}, 3500);
var shuffleStart = setTimeout(oneShuffle, x);
create new timers each time, so the first line (clearTimeouts();) makes no sense since the timers don't exist until next two lines.
You should put both timers outside the scope of a click handler, so all click invocations would reference same timers. Also all state (inMotin, spins, etc.) should exist outside the function scope, otherwise each click produces new, unrelated variables.
You should put clearTimeouts() inside your if, like this:
if(inMotion === true){
clearTimeouts();
console.log('Shuffling again');
//shuffle again
shuffleStart = setTimeout(oneShuffle, x);
}

Generate random number every x seconds and display it

Inside my App I have a sort of bottom bar Always shown, where I have a div with an h1, and a button. Everytime I click the button I coded and animation that do change the text of the h1 with a random number. Till here everything works fine.
My goal is to make this thing WITHOUT pressing a button, but just every x seconds during all the App execution. I tried to use "setInterval(func, ms);" I didn't get any error, but it just did it one time.
I think that my error is "where to put" the code. I don't understand this. So, I tried to put the code on the event handler of my button just to see if it works, but it did it one time anyway. I need that this function continues to be executed while the users do something else... It's like a clock inside an app: it should work continuosly while you do something else.
My function code:
function fraseCasuale(sel) {
var i = 1 + Math.floor(Math.random() * (groupedItems.length-1));
var oggetto = groupedItems.getAt(i);
if (sel === 1) {
document.getElementById("frasecasuale").textContent = oggetto.frase;
document.getElementById("autore").textContent = oggetto.nome;
document.getElementById("genere").textContent = oggetto.genere;
} else {
document.getElementById("frasecasuale2").textContent = oggetto.frase;
document.getElementById("autore2").textContent = oggetto.nome;
document.getElementById("genere2").textContent = oggetto.genere;
}
}
And then how I call it, for example:
setInterval(fraseCasuale(1), 5000);
My application is based on the grid template of Visual Studio 2012 for Windows Store aps. I added the bar I was talking above into "default.html", which is the container of the other pages.
Are you sure something like this doesn't work?
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var ms = 2000;
var func = function () {
var randNum = getRandomInt(1, 253); // Gets random number between 1 and 253
document.getElementById("element_id").innerHTML = randNum;
};
setInterval(func, ms);
http://jsfiddle.net/FQSAH/1/
The problem in your code is that you aren't passing a function to setInterval, you are passing the ONE TIME result of the function call fraseCasuale(1), so the result of that function is what is being passed to setInterval.
Since you want to pass a parameter to it, setTimeout lets you specify arguments after the function pointer and timeout interval, such as:
setInterval(fraseCasuale,5000,1);
If you are doing this in a defined 'Page' you'd do something like this in home.js
WinJS.UI.Pages.define("/pages/home/home.html", {
// This function is called whenever a user navigates to this page. It
// populates the page elements with the app's data.
ready: function (element, options) {
setInterval(this.fraseCasuale, 1000, 656);
},
fraseCasuale: function (sel) {
console.log(sel);
var i = 1 + Math.floor(Math.random() * (4 - 1));
var element = document.getElementById("updateMe");
element.textContent = i;
}
});
or if just using a default.js then you can throw your code there in app.ready, right above for ex. app.oncheckpoint (order doesn't actually matter above or below any function, just providing a place to show you an example)
So in default.js:
app.onready = function (args) {
//1 is a placeholder for your parameter
setInterval(fraseCasuale,5000,1);
};
This should work...
var id = window.setInterval(function(){randomNumber()},1000);
function randomNumber()
{
var rand = Math.floor(Math.random()*6)
//Do whatever you want with that number
}
Quick JSBin : http://jsbin.com/egajog/1/

Categories

Resources