setInterval() speeds up when using multiple from object method - javascript

I have been having problems with my setIntervals(). I know these issues appear a lot but I can't seem to work out what the exact problem with my implementation is. Every time I instantiate a new Obstacle() it clears the set interval used to rotate the instance of the obstacle, and the next instantiation of the obstacle seem to rotate twice as fast! I'm sure it's to do with scope but I'm a relative beginner so I'm not quite sure what's going on here. Any more info can be provided.
var obstacleCount = 1;
function Obstacle(){
this.angle = 0;
this.id = obstacleCount;
this.elPrefix = "cookie-";
this.el = '.' + this.elPrefix + this.id;
$('#game-wrapper').append('<div class="' + this.elPrefix + this.id + '"></div>');
obstacleCount += 1;
}
var intervals = new Array();
Obstacle.prototype.roll = function() {
self = this;
intervals[self.id] = setInterval(function(){
self.angle -= 3;
$(self.el).rotate(self.angle);
}, 5);
$(self.el).animate({
right: 1000
}, 4000, 'linear', function(){
$(self.el).remove();
clearInterval(intervals[self.id]);
});
};
var obstacles = new Array();
setInterval(function(){
obstacleID = obstacleCount;
obstacles[obstacleID] = new Obstacle();
obstacles[obstacleID].roll();
}, 1000);

In most games there is a single update loop that handles all of the update logic for your game. I would recommend using a single interval in which all objects are updated instead of giving each object it's own scheduled update via setInterval. You gain a few advantages from the update loop method:
Don't have to keep track of intervals.
Since since setInterval is not consistant with timing (it fires when the main script is finished executing and has some extra time before the next go around, but only if it's interval time is up. This means you cannot completely rely on it's timing being what you asked it to be.) you are better off having all your objects updated at the time so you are as consistant as you can be.
General pseudo code to get you started:
initialize objects
add all objects to an array
setInterval(updateObjects, 30);
updateObjects(){
for each object in array
object.roll();
}

Related

Creating a for loop that loops over and over =

So I have a weird problem (as I can do this using dummy code, but cannot make it work in my actual code) -
The concept is simple - I need a for loop that upon hitting its max "I" number reverts "I" to 0 again and creates a loop over and over -
DUMMY CODE:
for(i=0;i<10;i++){
console.log(i);
if(i === 10){
i = 0
}
}
Now for the longer code (sorry)
function reviewF(){
// add ID to each of the objects
reviews.forEach((e, i)=>{
e.id = i
})
// get the elements to be populated on page
var name = document.querySelector('p.name');
var date = document.querySelector('p.date');
var rating = document.querySelector('.rating_stars');
var review = document.querySelector('p.review_content_text');
// reverse the array - so the newest reviews are shown first (this is due to how the reviews where downloaded)
var reviewBack = reviews.slice(0).reverse();
// start the loop - go over each array - take its details and apply it to the elements
/**
* THIS IS WHAT I WOULD LIKE TO LOOP OVER FOREVER
*
* **/
for (let i = 0; i < reviewBack.length; i++) {
(function(index) {
setTimeout(function() {
// document.getElementById('reviews').classList.remove('slideOut')
name.classList.remove('slideOut')
date.classList.remove('slideOut')
rating.classList.remove('slideOut')
review.classList.remove('slideOut')
name.classList.add('slideIn')
date.classList.add('slideIn')
rating.classList.add('slideIn')
review.classList.add('slideIn')
name.innerHTML = reviewBack[i].aditional_info_name;
date.innerHTML = reviewBack[i].Date;
rating.innerHTML = '';
review.innerHTML = reviewBack[i].aditional_info_short_testimonial;
if(reviewBack[i].aditional_info_short_testimonial === 'none'){
reviewBack.innerHTML='';
}
var numberOfStars = reviewBack[i].aditional_info_rating;
for(i=0;i<numberOfStars;i++){
var star = document.createElement('p');
star.className="stars";
rating.appendChild(star);
}
setTimeout(function(){
// document.getElementById('reviews').classList.add('slideOut')
name.classList.add('slideOut')
date.classList.add('slideOut')
rating.classList.add('slideOut')
review.classList.add('slideOut')
},9600)
}, i * 10000)
})(i);
// should create a infinite loop
}
console.log('Loop A')
}
// both functions are running as they should but the time out function for the delay of the transition is not?
reviewF();
EDITS >>>>>>>>
Ok so I have found a hack and slash way to fix the issue - but its not dry code and not good code but it works.....
this might make the desiered effect easier to understand
reviewF(); // <<< this is the init function
// this init2 function for the reviews waits until the reviews have run then
// calls it again
setTimeout(function(){
reviewF();
}, reviews.length*1000)
// this version of the innit doubles the number of reviews and calls it after that amount of time
setTimeout(function(){
reviewF();
}, (reviews.length*2)*1000)
From trying a bunch of different methods to solve this issue something I noticed was when I placed a console.log('Finished') at the end of the function and called it twice in a row (trying to stack the functions running..... yes I know a horrid and blunt way to try and solve the issue but I had gotten to that point) - it called by console.log's while the function was still running (i.e. the set time out section had not finished) - could this have something to do with it.
My apologies for the rough code.
Any help here would be really great as my own attempts to solve this have fallen short and I believe I might have missed something in how the code runs?
Warm regards,
W
Why not simply nest this for loop inside a do/while?
var looping = True
do {
for(i=0;i<10;i++){
console.log(i);
}
if (someEndCondition) {
looping = False;
}
}
while (looping);
I would think that resetting your loop would be as simple as setting "i = 0" like in the dummy code. So try putting the following into your code at the end of the for loop:
if(i === 10){
i = 0;
}

Javascript setTimeout scope referencing wrong variables

I've written a little function to loop through a sprite sheet. Within the function I have a settimeout which cycles through the frames. Upon the last frame, the timeout is cleared, the counter is set to zero - and the animation begins again.
This works fine with one animation, but when I try and call many animations - they all start but fail to loop, apart from designSprite which loops quite happily. I call the designSprite anim last....
So I'm guessing the problem is due to variables being overwritten when I call a new intance of the function - setTimeOut referencing the new variables?? I've confused myself. I've had a stab at trying to fix it, but keep failing.
Thanks,
Rob
// Arrays to hold our sprite coordinates.
var animationSprite=[{"X":"-2","Y":"-2"},........ etc etc ];
var mediaSprite=[{"X":"-2","Y":"-2"},........ etc etc ];
var filmSprite=[{"X":"-2","Y":"-2"},........ etc etc ];
var designSprite=[{"X":"-2","Y":"-2"},........ etc etc ];
// call the loopAnim function, passing in the sprite array, and id of the div
loopAnim(animationSprite ,'#animationFrame')
loopAnim(mediaSprite ,'#mediaFrame')
loopAnim(filmSprite ,'#filmFrame')
loopAnim(designSprite ,'#designFrame')
function loopAnim(sprite , frameID) {
var totalFrames = sprite.length; // count how many 'frames' are in our sprites array.
var count = 0; // set up a basic counter to count which frame we're on.
var theLoop = function(){
// Move the background position of our frame by reading the X & Y co-ordinates from the sprites array.
$(frameID).css("background-position" , sprite[count].X + "px " + sprite[count].Y + "px");
count++; // increment the frame by 1 on each loop
// if count is LESS than total number of frames, set a timeout to keep running the "theLoop" function
if (count < totalFrames){
setAnim = setTimeout(theLoop, 60);
// if count is greater than the total number of frames - clear our timeout. Reset the counter back to zero, and then run our loop function again
} else {
clearTimeout(setAnim);
count = 0;
theLoop();
}
}
theLoop();
}
setAnim looks like it wasn't declared, meaning it's a global variable. This means all your calls to loopAnim are using and overwriting the same timer ID reference.

Destroy an object after set time

I have been looking around for this but have turned up a blank
is it possible in javascript to create an instance of an object which has a set time to live, after which it would be destroyed?
a case would be where a item is added to an array every 5 seconds and shown in the visual, each item then should be removed after it have been in view for a minute. I hesitate to run a timeout function checking the array every second to clear them..
OOP FTW. Why not create some sort of self removing object?
function SelfRemover(){//constructor
};
SelfRemover.prototype.addTo = function(arr) {
var me = this;
arr.push(me); //adding current instance to array
setTimeout(function() { //setting timeout to remove it later
console.log("Time to die for " + me);
arr.shift();
console.log(arr);
}, 60*1000)
}
Usage
var a = [];
setInterval(function(){new SelfRemover().addTo(a); console.log(a);}, 5*1000);

JavaScript - Timer Initiation

I'm trying to make my enemy fire every second. Right now - it's every frame.
Within my enemy object, I have a piece of code that is initiated when the player is within range:
this.shotBullet = false;
var object = this;
object.Fire();
This is the enemy fire function:
this.Fire = function(){
console.debug("Firing | Shot: " + this.shotBullet);
if(!this.shotBullet){
if(this.weapon == "pistol")
PistolEnemy(this);
this.shotBullet = true;
}
};
And my PistolEnemy function:
PistolEnemy = function(operator){
var user = operator;
console.debug("user:" + user.tag);
var bulletDamage = 1;
var bulletSpeed = 20;
var b = new Rectangle( user.x + (user.width / 2) - 4, user.y + (user.height / 2) - 4, 8, 8);
var velocityInstance = new Vector2(0, 0);
velocityInstance.x = Math.cos(user.rotation) * bulletSpeed;
velocityInstance.y = Math.sin(user.rotation) * bulletSpeed;
var bulletInstance = new Bullet(velocityInstance, b, "Enemy", bulletDamage, "blue");
/*audioPistol.volume = 0.5;
audioPistol.currentTime = 0;
audioPistol.play();*/
user.bullets.push(bulletInstance);
user.shotBullet = true;
};
I've tried playing around with the 'setInterval', but it doesn't work well. Most of the times, it waits for a second, then sprays a load of bullets.
All I want it for a enemy bullet to initiate every second.
Thanks
var triggerID = window.setInterval(function(){firing_clock()},1000);
function firing_clock()
{
// this will execute once per second....sort of
}
Mozilla window.setInteral doc
So, one thing you should known is if your browser gets busy it will get 'late'. Mozilla used to have an extra non-standard parameter detailing "actual lateness", but it no longer does - but the point was that you are asking the browser to try to do something once per second, but if it gets busy it will get behind or skip a few rounds (how the browser handles it differs by browser).
Ideally what you would do here is register your enemy object with a list that firing_clock() would work through to dispatch firing commands to all live enemies. This cuts overhead by only using one global timer, rather than one timer per object on screen.
Try this with just one hard-coded enemy and see how it works. If it still doesn't work, then it's a bigger problem as there is no javascript "guaranteed accurate timer" that I'm aware of.
But it should work, so long as things don't get too intense on the client's CPU, and having one global timer for ship firing should allow you to have a good number of ships firing away without too much ill effect.

How to optimize this js (now CPU is over 40% when the page is opened)

I have this piece of JavaScript on my page and it loads the CPU considerably. Is there any way to optimize the code? ( I'm using jQuery, so jQuery solutions will be fine )
function Particle() {
this.particleContainerWidth = $('#particle-container').width() - 100;
this.particleContainerHeight = $('#particle-container').height() - 100;
this.path = 'img/';
this.images = ['particle1.png', 'particle2.png', 'particle3.png', 'particle4.png'];
// Randomly Pick a Particle Model
this.image = this.images[randomInt(this.images.length)];
this.file = this.path + this.image;
// Create a Particle DOM
this.element = document.createElement('img');
this.speed().newPoint().display().newPoint().fly();
};
// Generate Random Speed
Particle.prototype.speed = function() {
this.duration = (randomInt(10) + 5) * 1100;
return this;
};
// Generate a Random Position
Particle.prototype.newPoint = function() {
this.pointX = randomInt(this.particleContainerWidth);
this.pointY = randomInt(this.particleContainerHeight);
return this;
};
// Display the Particle
Particle.prototype.display = function() {
$(this.element)
.attr('src', this.file)
.css('position', 'absolute')
.css('top', this.pointY)
.css('left', this.pointX);
$('#particle-container').append(this.element);
return this;
};
// Animate Particle Movements
Particle.prototype.fly = function() {
var self = this;
$(this.element).animate({
"top": this.pointY,
"left": this.pointX
}, this.duration, 'linear', function(){
self.speed().newPoint().fly();
});
};
function randomInt(max) {
// Generate a random integer (0 <= randomInt < max)
return Math.floor(Math.random() * max);
}
$(function(){
$('body').append('<div id="particle-container"></div>');
var total = 8;
var particles = [];
for (i = 0; i < total; i++){
particles[i] = new Particle();
}
});
You cannot make JavaScript consume less of your CPU. That is governed by the priority of the executing application in the OS kernel. The best you can hope for is to reduce execution time.
To improve your execution efficiency limit your usage of prototype and stop assigning values to properties. This method of coding has become popular because it is extremely clean and easy to read, but it horribly backwards to execute.
If you are capable of coding using only variables for assignment, if statements for decisions, and for loops for looping your code execution will be far faster. That will require you to write more code, however, and it will not be so pretty.
To improve output performance write all output segments each into an index of an array and use only a single join method when all output is created and a single innerHTML method to output this text to the page. This will reduce output execution by up to 4 times.
Have you thought about implementing this with a <canvas> version? It won't work in IE directly, of course, and off-hand I'm not sure whether it'd be faster or slower. You could also try it with Processing.
This would need a lot of changing and rewriting, but You can create a new easing function for jquery and post it to animate. Then every particle You have would just be once issued with animate() with Your easing function and the function has to be based on those:
random
current time (new Date()) modulo some number
a singleton holding individual directions
ideas:
Assuming You don't want to change Your code You can try setting the particle to fly with some random timeout when first running fly(). It could change the way it's all executed. No idea if it helps or makes it slower though ;)
Second thing is quality. jquery animate does it too smoothly. You can move Your particles instead of animating and just chande the distance to lower and increase speed and use setTimeout to make it move the same pace as now.

Categories