How can I create an update function in javascript/jquery?
An update function is a function that is run at each step in the game, say 60 times a second for example. It is used a lot in game development.
How can I make something like this in jquery?
Probably you need to use setInterval function.
But I would recommend to use requestAnimationFrame instead as it was designed for developing browser games and can perform 60 calls per second as you need.
why jQuery? just call a function with a frequency of 1000/60 msecs, e.g.
setInterval(function() {
...
}, 1000/60)
SetInterval will be useful to you in this instance.
You can use it like this -
var timer = setInterval(callback,delay);
This code will execute a function named callback every delay miliseconds.
To stop the timer, you can use the clearInterval() method.
clearInterval(timer);
As I stated, the intervals are defined in milliseconds so in order for your callback to execute 60 times a second you would need to pass 16 or 17 milliseconds as the delay parameter.
That will partially depend on your rendering method.
If you will be rendering your "game" in (for instance) a <canvas> element, you might want to use requestAnimationFrame (a javascript native function)
For more information see This helpfull article
Related
I am trying to use the dev console to give mario a mushroom every 5 seconds (in the browser game super mario html5)
I can give mario mushrooms manually by typing marioShroons(mario) but I would like to have it on loop so I don't have to pause the game every time I want a mushroom. I have tried a while loop and set timeout but I can't figure it out. The only coding languages I familiar with are c++ and html.
**
while(data.time.amount > 0) {
killOtherCharacters()
}
setTimeout(function() {
killOtherCharacters()
}, 1000);
I expected these lines of code to not give me a mushroom, but to automatically kill enemies. But on the first try (the while loop) it froze the tab and I had to reload the page.
With the set timeout, it didn't make any obvious results, it killed all near characters once and then stopped.
You tried using setTimeout, and it only worked once. This is to be expected, because:
Window.setTimeout() sets a timer which executes a function or specified piece of code once the timer expires
From MDN
What you need to do is use setInterval:
The setInterval() method...repeatedly calls a function or executes a code snippet, with a fixed time delay between each call.
From MDN
So in your console, you should write this:
setInterval(killOtherCharacters, 1000);
(I removed the anonymous function because it wasn't needed - you only need an anonymous function if you're passing parameters or doing multiple things. You do need to remove the () for this though).
And if you want to stop the function from executing, assign a variable to the interval:
var killCharacters = setInterval(killOtherCharacters, 1000);
Then call clearInterval upon this variable to clear the interval (stop the loop):
clearInterval(killCharacters);
The reason your while loop froze the page is because Javascript can only do one thing at a time and you told it to always run your while function, blocking all other Javascript from running on your site.
setTimeout is only run once after a set time (see documentation), if you want to run something every x miliseconds it's better to use setInterval instead.
var intervalID = window.setInterval(killOtherCharacters(), 500); //run this every 500 ms
Use setInterval if you want killOtherCharacters() to be called repeatedly.
const interval = setInterval(function() {killOtherCharacters() },1000);
Then when you want the function to stop being called:
clearInterval(interval);
I'm looking at some code that uses setInterval to call a function every 30 seconds, but it doesn't look like it's firing every 30 seconds, in fact it fires every 3 minutes roughly. I think it's because there are other functions enqueued and it takes a while to get to call this function. Please correct me if I'm wrong.
Is there any way to check what's there on the callback queue either visually or even something simple to dump every 1 sec to some log file?
You can use process._getActiveHandles() and process._getActiveRequests()
See this discussion in node.js mailing list.
update: there is a good package for this - https://github.com/mafintosh/why-is-node-running
You can use this to check that it is called e.g. every 30 seconds:
setInterval(function() { console.log(new Date());}, 30000);
I am trying to create a scenario where I have two variables (or more) both assigned to their own setInterval object and each setInterval object has a different function and a different millisecond value. The goal is to create a rhythm between the two by launching functions that play two different audio files repeatedly.
The current problem I've come across is this:
If one set interval is set to 1000 and the other is set to 500 each one doesn't start immediately. The millisecond delay is part of the start time. I want to know how to omit the delay on the start time so that both functions launch immediately but then they each keep there respective interval times.
The "logic" I've come up with so far is something along the lines of creating a function that immediately plays audio with no millisecond value and then have another function that is assigned to setInterval which begins playing x number of millisecond earlier on the next "beat" to make up the difference. I'm curious if the logic seems sound or if this is a problem in which a "conventional" javascript solution exist that I don't know about.It seems like there is an easier way.
I haven't begun coding yet albeit I didn't want to dig myself a hole before I have to if someone already has a fix for this.
Thanks
I avoid setInterval. Instead, i use setTimeout with such a pattern:
function someThing() {
// do something ...
setTimeout(someThing, 2000);
// or do something after setting the timeout ...
}
// either delay the start:
// setTimeout(someThing, 1000);
// or start right away
someThing()
But if you really want to use setInterval then a similar pattern works:
function someThing(firstTime) {
if (firstTime === true) {
console.log('setting interval for someThing');
setInterval(someThing, 1000);
}
console.log('someThing called');
}
someThing(true);
Is it possible to ser a function to start in a given date and hour? How?
I thought about setTimeout, but what's the maximum time I can set?
--update
By the way, it's for a desktop application.
I agree with JCOC611 - if you can make sure that your application does not close, then just get a Date object of when your alarm should go off and do something like this:
window.setTimeout(function() { soundAlarm() },
alarmDate.getTime() - new Date().getTime());
I see no reason for this not to work, but a lot of people exalt a timer based solution where you have a short lived timer that ticks until the set time. It has the advantage that the timer function can also update a clock or a countdown. I like to write this pattern like this:
(function(targetDate) {
if (targetDate.getTime() <= new Date().getTime()) {
soundAlarm();
return;
}
// maybe update a time display here?
window.setTimeout(arguments.callee,1000,targetDate); // tick every second
})(alarmDate);
This is basically a function that when called with a target date to sound an alarm on, re-calls itself every second to check if the time has not elapsed yet.
setTimeout(functionToCall,delayToWait)
As stated in Why does setTimeout() "break" for large millisecond delay values?, it uses a 32 bit int to store the delay so the max value allowed would be 2147483647
Does setTimeout() have a maximum?
http://www.highdots.com/forums/javascript/settimeout-ecma-166425.html
It may surprise you that setTimeout is
not covered by an ECMA standard, nor
by a W3C standard. There are some
holes in the web standards. This is
one of them. I'm looking to the WHAT
Working Group to fix this. See
http://www.whatwg.org/specs/web-apps/current-work/
There doesn't seem to be a problem in
setting the timeout value to something
that is vastly greater than the MTBF
of the browser. All that means is that
the timeout may never fire.
http://javascript.crockford.com/
-Douglas Crockford
As others have mentioned, this isn't the way to handle the situation. Use setTimeout to check a date object and then fire the event at the appropriate time. Some code to play with is linked below.
http://www.w3schools.com/js/tryit.asp?filename=tryjs_timing_clock
You should not relay on setTimeout for the actual alarm trigger but for a periodic function tracking the alarm. Use setTimeout to check the stored time for your alarm say every minute. Store that time in DB, file or server.
Is there any server component to this at all? You could use setInterval to call something serverside on a regular basis via ajax, then pull back a date object and once it's finally in the past you could trigger your "alarm"
Scenario:
I want to create a jQuery controllable jackpot "spinner" that will rapidly sequence a number of random images through a div before settling on one, with the delay interval between each equal but changeable. For mockup purposes, I'm simply changing CSS color classes to a box, although in the final I'll use background images.
I thought this would be a no-brainer to do with a loop. I'm sure there's a more efficient way to do this, but guessed the below would work fine. However, I discovered I have no way to control the CSS color swap speed. This whips through the color class changes instantly and just shows the last one. What I'd like is a delay where indicated.
jQuery delay() doesn't seem to work when chained with addClass(), though it works fine with effects. So I tried using window.setTimeout, but as far as I can see, in this context it requires a kludgey function call. The code as written below executes all the function calls after the loop has run. Is this a closure issue? Don't want to use setInterval because these will be limited iterations.
Thanks for any advice!
for (var j= 9; j >= 0; j--) {
$('#box1').attr('class', 'boxes'); // strips all current classes, replaces them with class 'boxes', which has general CSS characteristics
var numRand = Math.floor(Math.random() * 6);
var randomClass = colorArray1[numRand]; // pull random class from an array of six choices
$('#box1').addClass(randomClass);
// Everything above here works fine, would like loop delay here
// Tried using straight-up setTimeout -- doesn't appear to like loops
window.setTimeout(outerFunc, 1000);
};
function outerFunc() {
alert('nobody here but us chickens!');
};
If you want to use .delay() with a method like .addClass(), you can add it to the queue with jQuery's .queue() method.
$('#box1').delay(1000)
.queue(function( nxt ) {
$(this).addClass(randomClass);
nxt(); // allow the queue to continue
});
Otherwise, if I get what you want, you could multiply the 1000 ms for the setTimeout() by the current value of j, so that each time the duration increases.
window.setTimeout(outerFunc, (1000 * j));
setTimeout and setInterval work differently in javascript to the way you want to use them.
Both functions take the function that you pass in and attach them to the window DOM object. Then, after the delay you have passed in has passed, and when there is no other script currently running, they get called from the window object.
To get the functionality you are after, you will need to convert your code so that the jQuery addclass call is inside the function you are passing to setTimeout.
Perhaps recursion would work?
// this code is not tested
var j = 9;
function myFunc() {
// code here
j--;
if(j >= 0) setInterval(myFunc, 1000);
}
I haven't used the queue class in jQuery myself (first I've heard of it, but it sounds cool). That might be the better answer, but this should be a decent alternative if the queue doesn't work as expected.
UPDATE: I just noticed that in your code it looks like you are expecting setTimeout to work like Thread.Sleep in .Net. setTimeout doesn't work that way. It works more like Thread.Start where your code continues on as soon as you call it.