I am trying to make a simple hidden object game using javascript. When the user finds and clicks an image, I want 3 things to happen in the following order; a sound plays, the image size increases, and the image goes invisible. The problem I am running into is getting the 3 events to happen sequentially, not concurrent. Right now, seems that all three events happen all at the same time.
I've tried using setTimeout(), and while that does create a delay, it still runs all functions at the same time, even if each function is nested in setTimeout.
Example: (all this does is waits 1.5 sec then plays the sound and makes the image invisible):
function FindIt(image, id){
var t = setTimeout('sound()',10);
var b = setTimeout('bigger(' + image + ')',30);
var h = setTimeout('hide(' + image + ')',1500);
}
Below are the functions I am currently using and the actual results are: click the image, nothing happens for 2 seconds, then the sound plays and the image goes invisible.
function FindIt(image, id){
sound();
bigger(image);
hide(image);
}
function sound(){
document.getElementById("sound_element").innerHTML= "<embed src='chime.wav' hidden=true autostart=true loop=false>";
}
function bigger(image){
var img = document.getElementById(image);
img.style.width = 112;
img.style.height = 112;
}
function hide(id){
var ms = 2000;
ms += new Date().getTime();
while (new Date() < ms){} //Create a 2 second delay
var img = document.getElementById(id);
img.style.visibility='hidden';
}
Any guidance would be greatly appreciated!
To trigger things sequentially, you need to execute the second item some amount of time after the first one completes, execute the third item some amount of time after the second one completes, etc...
Only your sound() function actually takes some time, so I'd suggest the following:
function FindIt(image, id){
sound();
// set timer to start next action a certain time after the sound starts
setTimeout(function() {
bigger(image);
// set timer to start next action a certain time after making the image bigger
setTimeout (function() {
hide(image);
}, 1000); // set this time for how long you want to wait after bigger, before hide
}, 1000); // set the time here for how long you want to wait after starting the sound before making it bigger
}
FYI, the animation capabilities in libraries like jQuery or YUI make this sort of thing a lot easier.
Also, please don't use this kind of construct in your JS:
while (new Date() < ms){}
That locks up the browser for that delay and is very unfriendly to the viewer. Use setTimeout to create a delay.
For reference, using the animation libraries in jQuery, the jQuery code to handle a click on the object and then animate it over a 2 second period to a larger size, delay for 1 second, then slideup to disappear is as follows:
$("#rect").click(function() {
$(this).animate({height: 200, width: 400}, 2000).delay(1000).slideUp();
});
jQuery manages an animation queue and handles setting all the timers and doing all the sequencing and animation for you. It's a lot, lot easier to program and gives a very nice result.
You can see it work and play with it here: http://jsfiddle.net/kC4Mz/.
why don't use "event" approach. like onTaskDone();
function task1(arg, onTask1Done){
console.log(arg);
if(onTask1Done)onTask1Done();
}
task1("working", function(){console.log("task2");});
The Frame.js library is designed to elegantly handle situations like this:
function FindIt(image, id){
Frame(10, function(next) { sound(); next(); });
Frame(30, function(next) { bigger(image); next(); });
Frame(1500, function(next) { hide(image); next(); });
Frame.start();
}
Frame.js offers many advantages over using standard timeouts, especially if you are doing a lot of this kind of thing, which for a game, you likely are.
https://github.com/bishopZ/Frame.js
Related
Reference code:
function sleep( sleepDuration ){
var now = new Date().getTime();
while(new Date().getTime() < now + sleepDuration){ /* do nothing */ }
}
function submit_answer(label) {
let image = get_node('img.to_label')
let size = Math.floor(Math.random() * 500)
image.src = `http://via.placeholder.com/${size}x${size}`
setTimeout(sleep.call(this, 1000), 0)
}
submit_answer is called from a click handler.
Desired function: the image is rendered, and the user is forced to wait 1 second before interacting with the page in any way.
Actual function: the user waits 1 second, and the image loads.
I thought setTimeout would put sleep on a queue - I was hoping that the image would be rendered before they were made to wait. How can I force the image to render, and then force the user to wait?
setTimeout() and setInterval() take a function reference or code as a string (but, don't do that) as their first argument. Your code:
setTimeout(sleep.call(this, 1000), 0)
passes an actual function invocation of sleep and that's why you get sleep first (it's being called immediately) and the image load second. The return value from the function invocation is what winds up getting used as the function reference, but sleep doesn't return a value, so undefined winds up being passed to the timer and so nothing happens when the timer expires. The line would need to be:
setTimeout(function(){ sleep.call(this, 1000) }, 0)
so that a function reference would correctly be the first argument and the call to sleep wouldn't happen immediately.
From the docs:
Syntax:
var timeoutID = scope.setTimeout(function[, delay, param1, param2, ...]);
var timeoutID = scope.setTimeout(function[, delay]);
var timeoutID = scope.setTimeout(code[, delay]);
NOTE: code
An alternative syntax that allows you to include a string instead of a function, which is compiled and executed when the timer expires. This syntax is not recommended for the same reasons that make using eval() a security risk.
Also, setting a timer delay of 0 will never happen. The JavaScript runtime is synchronous and will only run the callback function specified in the timer when it has nothing else to do. As a result, you can never really know for absolute certain what the delay will wind up being. Think of the delay as the minimum amount of time you can expect to wait for your function to run. Having said that, I read somewhere that there was an absolute minimum of 16ms due to the latency between the JavaScript runtime and the browser's WebAPI.
Now, you are going to need to be able to trap the moment that the image actually gets rendered and that can be accomplished with .requestAnimationFrame().
Then, what you need to do is much simpler. You set your timer to start as soon as the image has finished loading and that is done by setting up a callback on the image's load event.
But, your code does nothing to prevent the user from interacting with the page, so you'll need to add a "mask" over the page that prevents interaction.
I've made the timer 3 seconds and given the mask a grey color in the snippet below to show the effect better.
var mask = document.getElementById("mask");
function startRender() {
// Rendering started, run callback when next render occurs
requestAnimationFrame(rendered);
}
function rendered() {
sleep(3000); // Render complete
}
// Nothing happens until the image fires off its load event...
document.querySelector("img").addEventListener("load", function(){
// Run callback when next render occurs
requestAnimationFrame(startRender);
});
function preventKeystrokes(evt){
preventDefault();
}
function sleep(duration){
mask.classList.remove("hidden"); // Show mask to prevent interactions
window.addEventListener("keydown", preventKeystrokes); // prevent keystrokes
// Count to three
setTimeout(function(){
mask.classList.add("hidden"); // Remove mask
window.removeEventListener("keydown", preventKeystrokes); // Enable keyboard
}, duration);
}
#mask { position:fixed; top:0; left:0; z-index:99; background-color:rgba(0,0,0,.6); width:100%; height:100%; }
.hidden { display:none; }
<button>Try to click me!</button>
<img src="http://imgsrc.hubblesite.org/hvi/uploads/image_file/image_attachment/30466/STSCI-H-p1801a-m-2000x1692.png" alt="big image">
<div id="mask" class="hidden"></div>
I'm trying to add sound and animation to this "ping-pong" (fizz-buzz) program. What I want to happen is for each item in the array (number/ping/pong/pingpong) the text fades in on the list while the sound and animation play.
What I'm getting is - the whole list fades in all at once, the sounds all play one at a time (and if the number entered is large it goes on forever) but the animation happens only once (apparently for just the last animation).
The whole project is at: https://github.com/karenfreemansmith/Epic-AdvancedJSwk1-PingPongCalculator, along with a link to a page with what is currently working. (Slightly earlier than the code below, which has only broken it in new ways.)
I've been trying to use setInterval and setTimeout to sync them all by calling a function that will show one element at a time with it's sound and animation:
var play=setInterval(function() {
var i=1;
output.forEach(item => {
showNext(item);
if(i>=output.length) {
clearInterval(play);
}
i++;
});
}, 1000);
And the function looks like this:
function showNext(item) {
acorn.style.animation= "";
acorn.style.webkitAnimation="";
if(item==="ping") {
window.setTimeout(playPing(), 1000);
} else if(item==="pong") {
window.setTimeout(playPong(), 1000);
} else if(item==="ping-pong") {
window.setTimeout(playVolley(), 1000);
} else {
window.setTimeout(playMiss(), 1000);
$("#pingpong").append("<p class='"+item+"'>" + item + "</p>");
}
}
and the play functions are all basically the same, but with different sounds:
function playPing() {
acorn.style.animation= "ping 1s linear";
acorn.style.webkitAnimation="ping 1s linear";
sndSlam1.currentTime = 0;
sndSlam1.play();
$("#pingpong").append("<p class='ping'>ping</p>");
}
I think I must be misunderstanding how the setTimeout is working. Why does the animation only play once? And why is there no pause between the elements being added to the list?
The problem here is because, yes, you do slightly misunderstand how setTimeout works.
What you do is call it like this:
window.setTimeout(playVolley(), 1000);
Which is equivalent to saying: "hey JS, immediately execute my function playVolley (since I use () to specify that I want it called), and THEN in 1000 seconds call whatever it has returned".
What, I strongly suspect, you really wanted to do, is:
window.setTimeout(playVolley, 1000);
Note how there are no "()" after playVolley. This is equivalent to saying: "hey JS, in 1000 seconds execute my cool func called playVolley".
If "passing function name without ()" doesn't make sense to you, that's okay, just read about "functions as first-class objects" (for example, here). The idea is just any function is really like a variable which holds a "function" in it, and you can pass it to anything takes "function as an input. Which, for example, setTimeout does - it needs a "function" and an "integer" to set a timeout.
But only fixing this won't help you. There's another problem here:
output.forEach(item => {
showNext(item);
...
}
See, here you effectively set output.length timeouts, all of them at once, to fire in 1000 seconds. Which they will do - in 1000 all of them will be executed simultaneously. So all you'll fix by the first fix is that all of your animations and sounds will play not immediately, but after a 1000ms delay.
What, I again strongly suspect, you wanted to do is to call every step of output array one by one, with 1000 delay between each other.
To achieve this you'll need to refactor the way you schedule your calls. Instead of scheduling them all at once, you'll need to chain them. A dirty, but simple example would be to have an index to current animation step, and when your playXXX finishes, it schedules next step to run, until all the steps are completed.
var currentAnimationStep = 0;
var output = ["ping", "pong", "ping", "pong"];
snowNext(output[currentAnimationStep]);
function showNext(item) {
+ if (item === undefined) {
+ return;
+ }
+
...
}
function playPing() {
acorn.style.animation= "ping 1s linear";
acorn.style.webkitAnimation="ping 1s linear";
sndSlam1.currentTime = 0;
sndSlam1.play();
$("#pingpong").append("<p class='ping'>ping</p>");
+ currentAnimationStep += 1;
+ showNext(output[currentAnimationStep]);
}
// All other playXXX functions will need the same call added
Again, this is a very dirty example (globals, eeeew), don't tell anybody I showed you this, but it can get you started, and when you'll get a hang of closures, you'll rewrite it to something more manageable.
I am writing some motor controls with node.js using cylon.js. I have a servo, which when you give it an angle to go to has a callback function. When it finishes that function, I want to do another reading, and give it a new angle, with the callback to do another reading...so forth and so on.
the current code is:
function ControlServo(servo, angleSensor){
robo.servo.angle(angleSensor.Read(), controlServo(servo, angleSensor));
}
That gets stack overflowed in like a quarter second.
It's not possible to do what you want to do with Cylon.js. Cylon.js's internal "write" operation "callback" is not async and doesn't get called when the move is mechanically completed. It gets called immediately after the write operation. Cylon can only write the angle value to the servo, which mechanically moves the horn at its max capable speed. If it's a slow servo, it could take 2 whole seconds from 0 to 180 degrees before it's actually mechanically complete. In the meantime, Cylon has already called the callback. The reason for this is because there is no way to generalize that callback behavior in a way that would be consistently correct for all servo models, without doing a little extra work.
In Johnny-Five we've implemented speed control that's enabled by providing a "time to complete" argument. This is done by dividing the distance to the new angle into steps to move in the specified "time to complete". A side effect of this process is that Johnny-Five servo instances can know when the move is mechanically complete, because the steps are smaller and the timing controlled. As a result, we have a "move:complete" event that emits when any timed move is completed.
var servo = new five.Servo(9);
servo.on("move:complete", function() {
// we've arrived!
});
// change takes 500ms to complete
servo.to(180, 500);
That can easily be combined with an analog sensor:
var servo = new five.Servo(9);
var sensor = new five.Sensor({
pin: "A0", scale: [ 0, 180 ]
});
servo.on("move:complete", function() {
update();
});
function update() {
// change takes 200ms to complete
servo.to(sensor.value, 200);
}
update();
Even simpler:
var servo = new five.Servo(9);
var sensor = new five.Sensor("A0");
sensor.scale(0, 180).on("change", function() {
servo.to(this.value);
});
A better way to solve this is using a timeout instead of recursing. This ends up calling your function on the next tick, which will never overflow.
function ControlServo(servo, angleSensor){
robo.servo.angle(angleSensor.Read(), function() {
setTimeout(function() { ControlServo(servo, angleSensor)}, 0);
});
};
You could shorten this by moving the timeout into the servo.angle function, but you might need it to be a callback for other uses. The method above requires no other change, since the callback is just setting the timeout.
Another option is setImmediate, which appears to put the function call at the end of the current tick, instead of the beginning of the next one. Since setTimeout will always introduce a slight delay, setImmediate might be faster; however, I don't know what other tradeoffs might be made using this as I haven't used it much myself.
I know this question has been asked a lot of times, and I have seen the solutions to them on SO as well as other forums. Most of the times the solution suggested is to use Web Workers.
A game I'm developing requires me to run multiple functions at the same time. One of them is an on click function and other is a setInterval.
My approach at doing this can be seen here in this JSFiddle. (keep clicking in gray area to make player jump).
The whole idea is to continuously spawn those blue obstacles after an interval of 1000ms.
In my earlier approach the obstacles would spawn only when I click to make player jump, otherwise they wouldn't as expected.
How can I run such two functions side by side in order to achieve
the aim of spawning obstacles while also making player jump.
Secondly, what would be the best approach to carry out this process
in view of game development i.e attaining a certain level of
efficiency so that the animations are not affected.
Here is the HTML and Javascript code I've been working on:
<div class="container">
<div class="player"></div>
<div class="obstacle-container">
<div class="obstacle"></div>
</div>
</div>
$.fn.animator = function () {
var hit_list, done = false;
$(".container").click(function () {
if (!done) {
$(".obstacle").stop().animate({
left: "-=105%"
}, 10000, "linear");
$(".player").stop().animate({
bottom: "+=100px"
}, {
duration: 300,
complete: function () {
$(".player").animate({
bottom: "0"
}, 800);
},
step: function () {
//Test for collision
hit_list = $(".player").collision(".obstacle");
if (hit_list.length !== 0) {
$(function () {
if (!done) {
$(".container").append("Game Over!");
return false;
}
});
done = true;
}
}
});
}
});
};
$(function () {
$('.container').animator();
});
var interval = null;
$(".obstacle-container").obstacle_generator();
$.fn.obstacle_generator = function () {
interval = setInterval(function () {
$(".obstacle-container").append('<div class="obstacle"></div>');
}, 1000);
};
The generic concept you want to investigate is known as a game loop.
Almost every game will be built using some variant of this system:
Initialise game
Loop:
Check for user input
Update any actors
Draw the scene
Wait until it's time to repeat
A game running at 60 frames per second would perform this loop 60 times per second, or about once every 16ms.
Compared to your original question, you wouldn't need to be running multiple execution threads (running multiple functions together) to achieve this.
You are, in a way, already using a similar loop. jQuery maintains its own loop for updating animations. Where you are checking for collisions as part of your animation step, this is the sort of thing you would do in a hypothetical Player.update() method. You want to move this code out of jQuery, and in to a loop that you control.
Since you're running in a browser, the generic game loop becomes a bit more simple:
Check for user input - this can still be handled by event handlers, jQuery or not. Rather than directly changing properties like CSS position, though, they should act upon the state of the game object. For example, by changing the velocity of a Player object.
Update any actors - the important part of your loop. You should check how many milliseconds have passed since you last looped, since the browser doesn't guarantee that your code will be run exactly, or at least, 60 times per second. You should then loop through all of your game objects and update them all. In your Player.update() method, you would want to move it according to its velocity and the time passed, for example.
Draw the scene - if you're using DOM elements, then the browser handles drawing for you, of course. If you were using a <canvas> element, then you would do drawing yourself as part of the loop here.
Wait until it's time to repeat - this will be up to the browser to do for you, as part of normal setInterval/setTimeout behavior.
A simple game loop in JavaScript can look like this:
var gameObjects = [];
// Initialise game, create player objects etc, add them to the array
var gameLoop = function() {
// Loop through gameObjects, and call their respective update methods
};
setInterval(gameLoop, 16); // Try to run the loop 60 times per second.
In a complex game, you wouldn't have just a basic array to hold all game objects, this is just an basic example.
Context
I've got about 10 complex graphs which take 5sec each to refresh. If I do a loop on these 10 graphs, it takes about 50 seconds to refresh. During these 50 seconds, the user can move a scrollbar. If the scrollbar is moved, the refresh must stop and when the scrollbar stops to move, the refresh occurs again.
I'm using the setTimeout function inside the loop to let the interface refresh.
the algorithm is :
render the first graph
setTimeout(render the second graph, 200)
when the second graph is rendered, render the third one in 200ms, and so on
The setTimeout allows us to catch the scrollbar event and to clearTimeout the next refresh to avoid to wait 50sec before moving the scrollbar...
The problem is that it does not run anytime.
Take the simple following code (you can try it in this fiddle : http://jsfiddle.net/BwNca/5/) :
HTML :
<div id="test" style="width: 300px;height:300px; background-color: red;">
</div>
<input type="text" id="value" />
<input type="text" id="value2" />
Javascript :
var i = 0;
var j = 0;
var timeout;
var clicked = false;
// simulate the scrollbar update : each time mouse move is equivalent to a scrollbar move
document.getElementById("test").onmousemove = function() {
// ignore first move (because onclick send a mousemove event)
if (clicked) {
clicked = false;
return;
}
document.getElementById("value").value = i++;
clearTimeout(timeout);
}
// a click simulates the drawing of the graphs
document.getElementById("test").onclick = function() {
// ignore multiple click
if (clicked) return;
complexAlgorithm(1000);
clicked = true;
}
// simulate a complexe algorithm which takes some time to execute (the graph drawing)
function complexAlgorithm(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
document.getElementById("value2").value = j++;
// launch the next graph drawing
timeout = setTimeout(function() {complexAlgorithm(1000);}, 1);
}
The code does :
when you move your mouse into the red div, it updates a counter
when you click on the red div, it simulates a big processing of 1sec (so it freezes the interface due to javascript mono thread)
after the freezing, wait 1ms, and resimulate the processing and so on until the mouse move again
when the mouse move again, it breaks the timeout to avoid infinite loop.
The problem
When you click one time and move the mouse during the freeze, I was thinking that the next code that will be executed when a setTimeout will occurs is the code of the mousemove event (and so it will cancel the timeout and the freeze) BUT sometimes the counter of click gains 2 or more points instead of gaining only 1 point due to the mouvemove event...
Conclusion of this test : the setTimeout function does not always release resource to execute a code during a mousemove event but sometimes kept the thread and execute the code inside the settimeout callback before executing another code.
The impact of this is that in our real example, the user can wait 10 sec (2 graphs are rendered) instead of waiting 5 seconds before using the scrollbar. This is very annoying and we need to avoid this and to be sure that only one graph is rendered (and other canceled) when the scrollbar is moved during a render phase.
How to be sure to break the timeout when the mouse move ?
PS: in the simple example below, if you update the timeout with 200ms, all runs perfectly but it is not an acceptable solution (the real problem is more complex and the problem occurs with a 200ms timer and a complex interface). Please do not provide a solution as "optimize the render of the graphs", this is not the problem here.
EDIT : cernunnos has a better explanation of the problem :
Also, by "blocking" the process on your loop you are ensuring no event can be handled until that loop has finished, so any event will only be handled (and the timeout cleared) inbetween the execution of each loop (hence why you sometimes have to wait for 2 or more full executions before interrupting).
The problem is exactly contains in bold words : I want to be sure to interrupt the execution when I want and not to wait 2 or more full executions before interrupting
Second EDIT :
In summary : takes this jsfiddle : http://jsfiddle.net/BwNca/5/ (the code above).
Update this jsfiddle and provide a solution to :
Mouse move on the red div. Then click and continue moving : the right counter must raise only once. But sometimes it raises 2 or 3 times before the first counter can run again... this is the problem, it must raise only once !
The BIG problem here is setTimeout is unpredictable once it started, and especially when it is doing some heavy lifiting.
You can see the demo here:
http://jsfiddle.net/wao20/C9WBg/
var secTmr = setTimeout(function(){
$('#display').append('Timeout Cleared > ');
clearTimeout(secTmr);
// this will always shown
$('#display').append('I\'m still here! ');
}, 100);
There are two things you can do to minimize the impact on the browser performance.
Store all the intances of the setTimeoutID, and loop through it when you want to stop
var timers = []
// When start the worker thread
timers.push( setTimeout(function () { sleep(1000);}, 1) );
// When you try to clear
while (timers.length > 0) {
clearTimeout(timers.pop());
}
Set a flag when you try to stop process and check that flag inside your worker thread just in case clearTimeout failed to stop the timer
// Your flag
var STOPForTheLoveOfGod = false;
// When you try to stop
STOPForTheLoveOfGod = true;
while (timers.length > 0) {
clearTimeout(timers.pop());
}
// Inside the for loop in the sleep function
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if (STOPForTheLoveOfGod) {
break;
}
// ...
}
}
You can try out this new script.
http://jsfiddle.net/wao20/7PPpS/4/
I may have understood the problem but assuming you are trying to block the interface after a click for a minimum of 1 second and unblocking it by moving the mouse (after that 1 second minimum):
This is not a good implementation of sleep, as you are keeping the process running the whole time (doing nothing != sleeping), this results in a waste of resources.
Why not create an overlay (a semi/fully transparent div), put it on top of the rest of the interface (position fixed, full width and full height) and use it to prevent any interaction with the underlying interface. Then destroy it when the conditions are right (a second has passed and the user moved the mouse).
This behaves more like a sleep (has some initial processing time but then releases the processor for a given amount of time) and should help you achieve the behavior you need (assuming i understood it right).
It has the added bonus of allowing you to give the user some visual cue that some processing is being done.
Edit:
Also, by "blocking" the process on your loop you are ensuring no event can be handled until that loop has finished, so any event will only be handled (and the timeout cleared) inbetween the execution of each loop (hence why you sometimes have to wait for 2 or more full executions before interrupting).
Surprising enough you have not figured out that, when you setTimeout(); you can input a check after that. A variable is true then trash the wait, or trash it. Now there is a method that you can check to scroll with a scroll bar. After you have checked it true inside a variabled using the means, then you will find this will repeat inifite times as they scroll the bar, making many executing times of 5 seconds. To fix this add a 1 second wait to make sure it doesn't over repeat. Your welcome :)
Any long-running function is going to tie up your browser window. Consider moving your complexAlgorithm() outside of your main javascript code using WebWorkers.
The answer is in your question
...the refresh must stop and when the scrollbar stops to move, the
refresh occurs again.
You should write complexAlgorithm in such way that you can almost instantly brake it in a middle (just when you know you will have to re run)
so main code should look something like
stopAllRefresh; //should instantly(or after completing small chunk) stop refresh
setTimeout(startRefresh, 100);
and render graph in small chunks (each runs < 1sec) in setTimeout
like
var curentGraph = 0;
var curentChunk = 0;
function renderGraphChunk(){
if (needToBreak) //check if break rendering
{exit};
// Render chunk here
render(curentGraph, curentChunk);
curentChunk +=1;
setTimeout(renderGraphChunk, 1);
}
this is just a idea sketch, real implementation can be completely different
What you want to do can not be done without web worker, that is only implemented in some latest browser specially Chrome.
Otherwise, you have to break your algorithm in queue. Just like jQuery UI puts every next animation calculation in queue. http://api.jquery.com/jQuery.queue/
It is a simple queue and next instruction set is queued with help of setTimeout.
for (i=0; i <1000; i++)
{
process (i) ;
}
Can be translated to
function queue(s,n, f)
{
this.i=s;
this.n=n;
this.f=f;
this.step = function(){
if ( this.i <this.n)
{
this.f(this.i);
this.i = this.i +1;
var t = this;
setTimeout( function ( ) { t.step(); } , 5);
}
}
this.step();
}
queue ( O, 1000, function(i){
process(i);
}) ;
This is just an example of how Synchronous for loop can be written to execute same logic asynchronously using smaller independent iteration.
Try and check out web workers. I think it will be useful in this situation.
http://en.wikipedia.org/wiki/Web_worker
http://www.html5rocks.com/en/tutorials/workers/basics/