Parellel.js doesn't work - javascript

I am trying to use Parallel.js (http://adambom.github.io/parallel.js/) in my code
In the html page the parallel.js script then in my code I placed these lines
parallelStarts = true;
var parallel = new Parallel(this.chromosomes, {
maxWorkers: 4,
evalPath: 'js/eval.js',
env: {
state: pslg.state,
totalDiffLevels: pslg.LevelGenerator.levelsOutline.length
}
});
parallel.map(function(chromosome) {
chromosome.CalculateFitness(global.env.state, global.env.totalDiffLevels);
return chromosome;
}).then(function(res) {
parallelStarts = false;
}, function(res) {
console.logError("Parallelism Failed");
});
while (parallelStarts) {}
I tried everything and nothing happens the function is not called by anything because it never change the parallelStarts variable to false.
Any help?

It's look like that infinite loop block all.
I suggest that use setInterval() or setTimeout() to check if parallelStarts variable changed his value, instead of infinite loop.

Related

Call back when using pre-defined function

I've declared a new function. Then I'm calling that function later. How do I run code only if the function I'm calling has completed.
this is my code
var callLogin = function() {
$(document).ready(function() {
if(document.getElementById("userLoggedIn") === null) {
$(".cover").fadeIn(200);
$(".sixPinInputContainer").fadeIn(200);
$("#pageBody").css("overflow", "hidden");
$('.sixPinInput').first().focus();
};
})
};
Then This is where I call It. The problem is that it's running the .load before it calls my pin container so even if pin is incorrect it runs code.
if (startBtn) {
callLogin()
$("#" + rowID).load("eventHandlersPHP/updateStart.php", {
roomID: id }, function(data, status) {
$("#notStartedCount").load("eventHandlersPHP/jobsNotStartedCount.php");
})
};
This is documented pretty well here. You could create some sort of action that'll trigger the one function, then it can call the other. Also, this will probably be a more helpful place for what it is you're trying to do.
-Gonzo

Mongoose callback not firing

This is the function in question
function matches_password(password)
{
var modified = false;
var matched = false;
User.count({password : password}, function (err, result)
{
modified = true;
console.log('hei');
if (err)
{
//error
}
else
{
if (result)
{
matched = true;
}
}
});
while (!modified)
{
console.log('sleeping');
sleep.usleep(100000);
}
return matched;
}
As you can see, I have a callback that updates some variables; the main flow of execution is delayed until the callback is fired. The problem is that 'hei' never appears in the console.
Removing the while loop fixes the problem, but I need it, or else matched is always false.
What's going on and what can I do to get around this setback?
It looks like you're running into a asynchronous issue. you could try using a setTimeout function inside your while loop that calls User.count(...)
for how setTimeout works with Node: How does setTimeout work in Node.JS?

Returning from a parent function from inside a child function - Javascript

I'm relatively new to coding in JavaScript, and I've came across a problem. I like to nest functions to keep things orderly, but how would I exit from a parent function from inside a child function?
example:
function foo1() {
function foo2() {
//return foo1() and foo2()?
}
foo2();
}
See update under the fold
You can't. You can only return from the child function, and then return from the parent function.
I should note that in your example, nothing ever calls foo2 (As of your edit, something does). Let's look at a more real example (and one that comes up a lot): Let's say we want know if an array contains an entry matching some criterion. A first stab might be:
function doesArrayContainEntry(someArray) {
someArray.forEach(function(entry) {
if (entryMatchesCondition(entry)) {
return true; // Yes it does <-- This is wrong
}
});
return false; // No it doesn't
}
You can't directly do that. Instead, you have to return from your anonymous iterator function in a way to stop the forEach loop. Since forEach doesn't offer a way to do that, you use some, which does:
function doesArrayContainEntry(someArray) {
return someArray.some(function(entry) {
if (entryMatchesCondition(entry)) {
return true; // Yes it does
}
});
}
some returns true (and stops looping) if any call to the iterator function returns true; it returns false if no call to the iterator returned true.
Again, that's just one common example.
You've referred to setInterval below, which tells me that you're almost certainly doing this in a browser environment.
If so, your play function almost certainly has already returned by the time you want to do what you're talking about, assuming the game has any interaction with the user other than alert and confirm. This is because of the asynchronous nature of the environment.
For example:
function play() {
var health = 100;
function handleEvent() {
// Handle the event, impacting health
if (health < 0 {
// Here's where you probably wanted to call die()
}
}
hookUpSomeEvent(handleEvent);
}
The thing is, that play will run and return almost immediately. Then the browser waits for the event you hooked up to occur, and if it does, it triggers the code in handleEvent. But play has long-since returned.
Make a note whether the parent function should also return.
function foo1() {
bool shouldReturn = false;
function foo2() {
shouldReturn = true; // put some logic here to tell if foo1() should also return
return;
}
if (shouldReturn) {
return;
} else {
// continue
}
}
It only says that you can't return the parent function in the child function, but we can do a callback and make it happen.
function foo1(cb = () => null) {
function foo2() {
cb();
}
foo2();
}
foo1(() => {
// do something
});
We can use Promises for this:
const fun1 = async () => {
const shouldReturn = await new Promise((resolve, reject) => {
// in-game logic...
resolve(true)
})
if(shouldReturn) return;
}
if you wanna return from the parent function, then just resolve with true
Based on your comment, something like this might work as a main game loop.
function play() {
var stillPlaying = true;
while(stillPlaying) {
... play game ...
stillPlaying = false; // set this when some condition has determined you are done
}
}

JS will not loop, stops after first loop

I've written the code below to act as a simple slideshow in the header of a clients website. Now, the only problem is when I put it into a for or a while loop it gets to the end of the first loop and then stops.
I've tried using calling togglinga() in the last callback, I've tried, wrapping the whole thing in a for and while loop, I've tried creating a different function that calls this one and then using that same function name in the final call back but get the same result everytime. I'd really appreciate someone casting their eye over this to see if they can see anything I can't....
function triggerAnimation(){
$("#logoareacontainer").delay(15000).fadeOut(3000, function() {
$("#title-1").fadeIn(0).delay(0, function() {
$("#cdsl-1-1").fadeIn(1000).delay(2000).fadeOut(0, function(){
$("#cdsl-1-2").fadeIn(0).delay(2000).fadeOut(0, function(){
$("#logoareacontainer").fadeIn(1000).css({display:'block'})
})
})
})
})
}
Much shorter and easier if you break this into functions that can be called in a cyclical manner.
Note that .delay() doesn't accept a callback function, which was a big part of the problem.
Here's a demo: http://jsfiddle.net/kjaHZ/
// for each "title-", keep track of how many "cdsl-"s there are
var titles = [null, 4, 2, 2, 2, 1, 1];
start();
// start it off
function start() {
$("#logoareacontainer").delay(1500).fadeOut(3000, function () {
doTitle(1);
});
}
// this starts a "title-" section
function doTitle(i) {
if (i < titles.length) {
// do the "title-" for the given "i" variable
$("#title-" + i).fadeIn(0, function () {
// after fading in, do the "cdsl-" ids
doCDSL(i, 1);
});
} else {
// or if "i" is >= titles.length, we're done
$("#logoareacontainer").fadeIn(1000).css({display:'block'});
}
}
// this starts a "cdsl-" section
function doCDSL(i, j) {
$("#cdsl-" + i + "-" + j).fadeIn(1000)
.delay(2000)
.fadeOut(0, function () {
if (j < titles[i]) {
// move to the next "cdsl-"
doCDSL(i, j+1);
} else {
// or do the next "title-"
$("#title-" + i).fadeOut(1000).css({display:'none'})
doTitle(i+1);
}
})
}
although your code is pretty awfull here u are :) u missed ()
function togglinga(){ triggerAnimation(); };
You can't put the code in a loop, because it is asynchronous. The loop would just start all the animations at once, because the outermost call won't wait until all the animations are complete.
At the innermost level, just call triggerAnimation to make it restart.

How to clear a javascript timeout thats set within a function

I have a recursive type function in Javascript that runs like this:
function loadThumb(thumb) {
rotate=setTimeout(function() {
loadThumb(next);
}, delay);
}
Note: I've simplified the function to make it easier to read.
I have "a" tags called like this
Load thumb 3
However, they don't clearout the timer, the timer continues to cycle through the function irregardless of the clearTimeout() being called.
Any ideas why? I think it might have something to do with a scope problem or something like that.
Yeah, you need to make rotate a global variable. Simply declare it outside the function like so:
var rotate;
var delay = 1000;
function loadThumb(thumb) {
alert("loading thumb: " + thumb);
rotate = setTimeout(function() {
loadThumb(thumb + 1);
}, delay);
}
Also, you need to make sure you clear the timeout before you call loadThumb. Otherwise you'll clear the timer you just started.
Load thumb 3
fiddle: http://jsfiddle.net/63FUD/
it may be the issue of scope so make rotate as global variable and call clearTimeout(rotate);
refer clearTimeout() example
It may be a scoping issue if you are not declaring rotate externally.
Try this:
var rotate = 0;
function loadThumb(thumb) {
rotate=setTimeout(function() {
loadThumb(next);
}, delay);
}
Return false on the link
Since you are not using var rotate, it should not be a scoping issue since rotate would be in the window scope. Can you show the complete code?
It is considered poor coding to inline the script - you should attach the event handler onload of the page
Also you should not have the setTimeout inside a function that might be called for one image
Try this:
var rotate,next=1;
function loadThumb(thumb) {
if (thumb) ... use thumb
else ... use next
}
function slide() {
rotate=setInterval(function() {
loadThumb();
next++;
if (next>=images.length) next=0;
}, delay);
}
window.onload=function() {
var links = document.getElementsByTagName("a");
if (links[i].className==="thumbLink") {
links[i].onclick=function() {
var idx = this.id.replace("link","");
loadThumb(idx);
clearInterval(rotate);
return false;
}
}
document.getElementById("start").onclick=function() {
slide();
return false;
}
document.getElementById("stop").onclick=function() {
clearInterval(rotate);
return false;
}
slide();
}
assuming
Start
Stop
Show 1
Show 2
Show 3
If you have to manage multiple timeouts, you can use an object in the global scope and some custom methods to create and remove your timeouts. To access the methods you can either put the calls in the onclick handler of your links (like in the example), or use a library like jQuery to bind them.
<script type="text/javascript">
var timeouts = timeouts || {};
function createTimeout(name, milliseconds, callback) {
timeouts.name = setTimeout(callback, milliseconds);
}
function removeTimeout(name) {
if (typeof(timeouts.name) !== undefined) {
clearTimeout(timeouts.name);
timeouts.name = undefined;
}
}
createTimeout('foo', 5000, function() {
alert('timeout')
});
</script>
i have also posted an example on jsFiddle http://jsfiddle.net/AGpzs/
I'm not sure what exactly you are doing, because as far as I can see you didn't post all the code, but this looks better for me:
function loadThumb(thumb) {
return setTimeout(function() {
loadThumb(next);
}, delay);
}
and then:
Load thumb 3

Categories