animate javascript timing delay problem
I'm having a problem understanding the use of the setInterval() command. (This is most likely because I don't properly understand how javascript timing works – I'm new to this!)
Here's what I want to happen:
- on clicking the play button, a variable myTimer starts (A)
- after each interval of 1000 milliseconds the variable year increases by 1
- the new value of year is displayed in the yearTextField.text text box
- an instance of the symbol sibling is added to the field siblingField
I thought I could make this work by using setInterval to run the function yearIncrease after each interval of 1000 milliseconds (see below). But instead it skips over the year 1973 and does not add the symbol.
Is the script trying to repeatedly run the if(year = 1973){} loop in yearIncrease()? and if so how might I avoid this i.e. just call another function once in the middle of each interval called by setInterval? I suppose what I'm really asking is: how do you create a delay before calling a number of functions?
thanks in advance for any help...
var myTimer;
var stageHeight = stage.canvas.height;
var stageWidth = stage.canvas.width;
var currentYear = 2017;
var year = 1971;
var yearTextField = this.yearText;
yearTextField.text = year;
var sibling1Added = false;
var sibling2Added = false;
var siblingField = new createjs.Container();
siblingField.regX = stageWidth/2;
siblingField.regY = stageHeight/2;
this.familyContainer.addChild(siblingField);
this.playBtn.addEventListener("click", playClicked.bind(this));
function playClicked() {
myTimer = setInterval(yearIncrease, 1000); /*A*/
}
function yearIncrease() {
year = year + 1;
yearTextField.text = year;
if(year = 1973){
if(sibling1Added = false){
addSiblings(1);
sibling1Added = true;
}
}
}
function addSiblings(siblings) {
for(var i=siblings-1; i>=0; i--) {
var sibling = new lib.sibling();
sibling.x = random(0, stageWidth);
sibling.y = random(-1000, stageHeight);
siblingField.addChild(sibling);
}
}
function random(min, max) {
return Math.floor(Math.random()*(max-min+1)+min);
};
