I'm making a game for a school project. The premise is that there will be enemies coming from the right side of the screen, and you will have to kill them. I've managed to create them so they are shown, but i can't manage to make them not come in at the same time.
Any tips on how i should go on with this?
(Sorry if this is badly formulated, i am very new to these things)
I've tried different ways of achieviving my goal trough using the elapsedTime function but i can't seem to make it work in the slightest.
function createEnemy() {
for(var i = 0; i < antallFiender; i++) {
var nyFiende = document.createElement("img");
nyFiende.setAttribute("src", "tenor.gif");
nyFiende.setAttribute("class", "zombie");
nyFiende.style.top = Math.floor(Math.random()*800) + "px";
barnetEl.appendChild(nyFiende);
}
var zombieEl = document.querySelectorAll(".zombie");
}
You can use JavaScript setInterval function. With this function you can pass a callback in the first parameter, and a time interval (in miliseconds) as the second parameter, that is the time between the calls of your callback. So it will be something like this:
function createEnemy() {
var nyFiende = document.createElement("img");
nyFiende.setAttribute("src", "tenor.gif");
nyFiende.setAttribute("class", "zombie");
nyFiende.style.top = Math.floor(Math.random()*800) + "px";
barnetEl.appendChild(nyFiende);
var zombieEl = document.querySelectorAll(".zombie");
}
setInterval(createEnemy, 1000);
This way, every 1 second your function will be called to create one enemy.
If you want to stop the function from being called, you should assign the interval to a variable, so you can use clearInterval to stop it, like this:
var enemyInterval = setInterval(createEnemy, 1000);
clearInterval(enemyInterval);
Hope it helps you.
Related
I have been working on my first major programming project and so far it has been going pretty well. My goal is to have an animation run until either an event is triggered or 15 seconds have passed. After the animation times out I want to animation to repeat. My current solution to the plan is shown below.
var animationSpeed = 40;
var animationTimout = 375;
var testTime = 1;
//some more set up variables
function onClick() {
startDrive();
setTimeout(startDrive, 15000); //****
}
function startDrive() {
var Driving = setInterval(carDriving, aniSpeed);
}
function carDriving() {
testLocation();
drawCar();
angleCalc();
newLocation();
getInfo();
}
function testLocation() {
//this code gets information on whether or not the animation should be stopped
testTime = testTime + 1
if(a === 1 || testTime > animationTimeout) {
//a test to cancel the animation, the other variables test to
clearInterval(Driving);
}
}
function drawCar() {
//draws the car
}
function angleCalc() {
//gets some info on how to move the car
}
function newLocation() {
//decides on new coords for the car based on angleCalc();
}
function getInfo() {
//gets some info I plan to use later in the project
}
When I run the code without the starred line, the whole thing works. The car animates as I want it to and stops if the conditions for stopping are met. The car freezes where it was on the canvas, and it seems as if the interval was cleared. When I add the starred line of code, the animation seems to work, but it runs twice as fast as before. I am utterly lost and nothing I try works. Please help.
The problem is likely due to the local variable defined here:
function startDrive() {
var Driving = setInterval(carDriving, aniSpeed);
}
The variable Driving is only defined in the function startDrive, it's a local variable because you are using var to define it inside the function. So when you attempt to access it inside testLocation() you are not accessing the same variable. In fact when you do clearInterval(Driving) the variable Driving isn't defined. A simple solution would be to make Driving global by removing the var:
function startDrive() {
Driving = setInterval(carDriving, aniSpeed);
}
Or you can pass the timer as a parameter inside the testLocation function. This way you will be clearing the interval properly.
this is my javascript code only work on click event and i want to make this auto slideshow. please help me i have no knowledge how to do it..
var wflSliders = ({});
var wflSlider = new Class({
Implements:[Options,Events],
initialize:function(options){
this.setOptions(options);
if(this.options.ribbon_behavior == 'scroll'){
this.wrapper = $('rand_products_wfl_'+this.options.id);
if(this.wrapper){
this.ribbon = this.wrapper.getElement('.jspw_ribbon');
this.scroll_r = this.wrapper.getElement('.jspw_scroll');
this.lt = this.wrapper.getElement('.jspw_ribon_button_lt');
this.rb = this.wrapper.getElement('.jspw_ribon_button_rb');
this.blocks = this.wrapper.getElements('.jspw_prod');
var blockSize = this.blocks[0].getComputedSize();
var dim = (this.options.orientation == 'hor')?'x':'y';
if(this.options.effect_block == 'single'){
this.offset=(dim=='x')?blockSize.totalWidth:blockSize.totalHeight;
}
One way to approach is that you can use a built-in function called setInterval in Javascript and after wrapping your code in a function call it in the interval you desire to have your slideshow speed.
Like the following:
setInterval(function(){
slideShow(); // Every second the function is called
},1000);
Check the documentation here for more understanding: MDN Documentation for setInterval function
UPDATE: Givi just proved to me (in the comments of my answer) that my answer was not right. It has high risk that you use my suggested approach and better to use setTimeout recursively like this:
function slideShow() {
setTimeout(function() {
slideShow();
}, 1000);
}
you can us slide show plugin. Good luck
I want to have multiple numbers on my web page "spin up" as the page loads, giving an impression like a fruit machine.
This involves a simple function with a delayed loop. The way to do this seems to be to use setTimeout recursively. This works fine for just one number on the page.
However for multiple numbers spinning at the same time, each needs its own spinner object. I used prototypes like this:
var Spinner = function(id){
this.element = $('#' + id);
this.target_value = this.element.text()
this.initial_value = this.target_value - 30;
};
Spinner.prototype.spinUp = function() {
loop(this.element);
function loop(element) {
element.html(this.initial_value += 1);
if (this.initial_value == this.target_value) {
return;
};
clr = setTimeout(loop(element), 30); // 30 millisecond delay
};
};
var Spinner1 = new Spinner('number')
Spinner1.spinUp();
However putting a recursive function inside the prototype method causes a big crash. Can you see a way around this?
Many thanks!
Derek.
A couple of issues:
loop() is not how you pass a function, it's how you invoke a function.
You are not calling the function as a method of the object
Try this:
Spinner.prototype.spinUp = function() {
var loop = function() {
this.element.html(this.initial_value += 1);
if (this.initial_value == this.target_value) {
return;
};
setTimeout(loop, 30); // 30 millisecond delay
}.bind(this); //Just flat out bind the function to this instance so we don't need to worry about it
loop();
};
Demo http://jsfiddle.net/KAZpJ/
When you say:
clr = setTimeout(loop(element), 30);
you are "calling" the function (then and there), and passing the value it returns as the first parameter to setTimeout(..).
You would want an anonymous function doing that job:
setTimeout(function(){loop(element);}, 30);
I have a website where they want a news ticker. Currently, I have a array that populates it, and every x seconds, I want the news story to change.
function startNews(stories) {
}
I am aware that you can use setInterval, but it has to go through a new function and you can't specify certain javascript in the same function to fire when it does.
What are you suggestions?
Thanks!
You should use either setInterval() or repeated calls to setTimeout(). That's how you do something in javascript at some time in the future.
There are no limitations on what you can do with either of those timer functions. What exactly do you think you cannot do that is making you try to avoid them?
Here's a pseudo code example:
var newsArray = []; // your code puts strings into this array
var curNewsIndex = -1;
var intervalID = setInterval(function() {
++curNewsIndex;
if (curNewsIndex >= newsArray.length) {
curNewsIndex = 0;
}
setTickerNews(newsArray[curNewsIndex]); // set new news item into the ticker
}, 5000);
or it could be done like this:
var newsArray = []; // your code puts strings into this array
var curNewsIndex = -1;
function advanceNewsItem() {
++curNewsIndex;
if (curNewsIndex >= newsArray.length) {
curNewsIndex = 0;
}
setTickerNews(newsArray[curNewsIndex]); // set new news item into the ticker
}
var intervalID = setInterval(advanceNewsItem, 5000);
You should whenever possible use setTimeout. If your function takes longer to run than the interval, you can run into a constant 100% cpu usage situation.
Try this code:
http://jsfiddle.net/wdARC/
var stories = ['Story1','Story2','Story3'],
i = -1;
(function f(){
i = (i + 1) % stories.length;
document.write(stories[ i ] + '<br/>');
setTimeout(f, 5000);
})();
Replace document.write with your function.
I began writing a simple animation class in JS, which utilizes Zepto.js animation capabilities but adds timeline-like capability to it.
The timeline itself is a simple array, that executes functions embedded in it when it's play() function is called:
play : function(callback){
for(var i=0; i<Animator.timeline.buffer.length; i++){
Animator.timeline.buffer[i].animation();
}
if(callback){
callback();
}
}
The setTimeout goes directly in the animation:
alpha : function(parameters, callback, delay){
var target = parameters.target;
var duration = parameters.duration;
var easing = parameters.easing;
var value = parameters.value;
if(delay){
setTimeout(function(){run();},delay*1000);
} else {
run();
}
function run(){
$(target).anim({opacity:value},duration,easing);
if(callback){
callback();
}
}
}
So basically, the timeline just runs the setTimeout-ed functions which are placed in it's buffer array.
This approach works (almost) as intended with WebKit animations, but i've run into a few problems when doing image sequences (animations using setInterval which change the image's src). As JS timers don't guarantee execution in their appointed time, sometimes animations run late, likely because of the embedded setInterval inside them.
Any ideas on how to solve this? I am aware that embedding all animations as callbacks inside one another would solve much of the issues, but i don't really know how to do that from inside the timeline loop. Also, it would quickly become an unreadable mess of callbacks if I call all functions in a direct manner (without using the timeline).
For reference, the sequence function of my animator class:
sequence : function(parameters, callback, delay){
var target = parameters.target;
var path = parameters.path;
var baseName = parameters.baseName;
var digits = parameters.digits;
var extension = parameters.extension;
var frames = parameters.frames;
var loop = parameters.loop;
if(parameters.interval){
var _interval = parameters.interval
} else {
var _interval = 15;
}
var currentFrame = 0;
var imageUrl = '';
var fileName = baseName;
for(var i=0; i<=digits; i++){
fileName+='0';
}
if(delay){
setTimeout(function(){runSequence();},delay*1000);
} else {
runSequence();
}
function runSequence(){
var interval = setInterval(function(){
if(currentFrame >= frames){
currentFrame = 0;
if(!loop) {
clearInterval(interval);
if(callback){
callback();
}
}
} else {
imageUrl = path+fileName.substring(0, fileName.length-currentFrame.toString().length)+currentFrame+"."+extension;
$(target).attr('src',imageUrl);
currentFrame++;
}
},_interval);
}
}
Also, a sample of an animation created by using this class:
Animator.timeline.append(function(){
Animator.alpha({'target':'#logo', 'value':1, 'duration':1, 'easing':'ease-out' });
});
Animator.timeline.append(function(){
Animator.sequence({'target':'#sequence', 'path':'images/sequences/index/', 'baseName':'nr1_', 'digits':3, 'extension':'png', 'frames':50},'',1.5);
});
Animator.timeline.append(function(){
Animator.scale({'target':'#text', 'width':.5, 'height':.15, 'duration':1, 'easing':'ease-in-out'},'',3.2);
});
Animator.timeline.append(function(){
Animator.alpha({'target':'#link', 'value':1, 'duration':1,'easing':'ease-out'},'',4.7);
});
Animator.timeline.play();
As an additional note, I was aiming to create something similar to GreenSock in AS3, if that helps.
Thanks.
Accurate setInterval can be simulated by compensating for the time it takes to execute every iteration, maybe this gist I wrote can help you:
https://gist.github.com/1185904