Game Screeps. Error during simulation. CPU limit reached - javascript

I'm going throw Screeps (http://screeps.com/) simulation. I've stick on stage when I need to send worker to harvest resources. So I put code from the tip to the script tab, code is:
var creep = Game.creeps.Worker1;
var sources = creep.room.find(Game.SOURCES);
creep.moveTo(sources[0]);
creep.harvest(sources[0]);
My creep had started move to source, but then it froze and I got error (light red text) in console:
CPU limit reached
What I need to do to finish this step and why I'm getting this error?

It's a limitation of the Simulation Room mode. Commit the scripts, refresh the page and start simulating again and it should work.

From the documentation:
Please remember that the exact duration of the execution of your
script is limited by the CPU time available in your service plan. In
case of exceeding the limit, the script execution will be stopped.
The exception is the Simulation Room where the script execution is always limited by 5 seconds.
So it seems that your creep can't find anything to harvest within five seconds

This appears to be a bug in Internet Explorer 11 (and probably older versions too but I don't have older versions installed). I would create a creep and everything would be fine and dandy until sometime between moving to and starting to collect from a source at which point the entire thing would freeze. I think this is just lazy programming because I was able to get everything working by switching to Chrome 39.blah.blah.blah. If you're not using Chrome I would suggest using it for this game.

Related

"ResizeObserver - loop limit exceeded" | API is never used

I am running a hybrid PhoneGap app (for a several years, running Cordova Android 6.1.2, more recently 9.0); for years, our #1 javascript error by a significant margin has been
ResizeObserver loop limit exceeded
However, the key distinction for my issue compared to the many other reports found on Google of this error is is that there are 0 instances of ResizeObserver being used anywhere in my code. Searching my entire computer, the only instance of ResizeObserver showing up anywhere is a random Steam file. Looking at my app while it's running, setting window.ResizeObserver = undefined doesn't break/do anything and document.resizeObservers (per the W3C documentation) returns nothing.
I have seen this post, which seems to be the canonical one for this error: ResizeObserver - loop limit exceeded . The answer of "This error means that ResizeObserver was not able to deliver all observations within a single animation frame. It is benign (your site will not break)." would be sufficient for me if I was actually using ResizeObserver. Since I am not using it, I am concerned that this error showing up is indicative of something larger going wrong.
There is no discernible pattern from our users' Chrome version/locale/time zone/Android version/etc/etc, unfortunately.
I've researched this API extensively and have found nothing that would indicate to my issue; either why there would be some sort of phantom ResizeObserver running and/or why that error would show up in an app that doesn't use that API.
Any help here (even just a vague direction to look at) would be very much appreciated. Thanks so much!
https://bugs.chromium.org/p/chromium/issues/detail?id=809574
Even the browser's Shadow DOM may be using this API, and cause this error to fire.
You can still safely ignore it.

How to optimize "Parse HTML" events?

While profiling my webapp I noticed that my server is lighting fast and Chrome seems to be the bottleneck. I fired up Chrome's "timeline" developer tool and got the following numbers:
Total time: 523ms
Scripting: 369ms (70%)
I also ran a few console.log(performance.now()) from the main Javascript file and the load time is actually closer to 700ms. This is pretty shocking for what I am rendering (an empty table and 2 buttons).
I continued my investigation by drilling into "Scripting":
Evaluating jQuery-min.js: 33ms
Evaluating jQuery-UI-min.js: 50ms
Evaluating raphael-min.js: 29ms
Evaluating content.js: 41ms
Evaluating jQuery.js: 12ms
Evaluating content.js: 19ms
GC Event: 63 ms
(I didn't list the smaller scripts but they accounted for the remaining time) I don't know what to make of this.
Are these numbers normal?
Where do I go from here? Are there other tools I should be running?
How do I optimize Parse HTML events?
For all the cynicism this question received, I am amused to discover they were all wrong.
I found Chrome's profiler output hard to interpret so I turned to console.log(performance.now()). This led me to discover that the page was taking 1400 ms to load the Javascript files, before I even invoke a single line of code!
This didn't make much sense, so revisited Chrome's Javascript profiler tool. The default sorting order Heavy (Bottom Up) didn't reveal anything meaningful, so I switched over to Chart mode. This revealed that many browser plugins were being loaded, and they were taking much longer to run than I had anticipated. So I disabled all plugins and reloaded the page. Guess what? The load time went down to 147ms.
That's right: browser plugins were responsible for 90% of the load time!
So to conclude:
JQuery is substantially slower than native APIs, but this might be irrelevant in the grand scheme of things. This is why good programmers use profilers to find bottlenecks, as opposed to optimizing blindly. Don't trust people's subjective bias or a "gut feeling". Had I followed people's advise to optimize away JQuery it wouldn't have made a noticeable difference (I would have saved 100ms).
The timeline tool doesn't report the correct total time. Skip the pretty graphs and use the following tools...
Start simple. Use console.log(performance.now()) to verify basic assumptions.
Chrome's Javascript profiler
Chart will give you a chronological overview of the Javascript execution.
Tree (Top Down) will allow you to drill into methods, one level at a time.
Turn off all browser plugins, restart the browser, and try again. You'd be surprised how much overhead some plugins contribute!
I hope this helps others.
PS: There is a nice article at http://www.sitepoint.com/jquery-vs-raw-javascript-1-dom-forms/ which helps if you want to replace jQuery with the native APIs.
I think Parse HTML events happen every time you modify the inner HTML of an element, e.g.
$("#someiD").html(text);
A common style is to repeatedly append elements:
$.each(something, function() {
$("#someTable").append("<tr>...</tr>");
});
This will parse the HTML for each row that's added. You can optimize this with:
var tablebody = '';
$.each(something, function() {
tablebody += "<tr>...</tr>";
});
$("#someTable").html(tablebody);
Now it parses the entire thing at once, instead of repeatedly parsing it.

analyzing performance of javascript on mobile

Is there any possibility of analyzing performance of javascript on mobile. Like I have a situation where say a list is rendered quite slowly on mobile (like 3-4 minutes).
Initially i thought its because of the data model and kind of query i am using is causing the delay, but when i took database traces all the query execution is really fast.
I also got hold of n/w trace of attached device (which is simulator in my case) and could see all the data being buffered in under 3 secs. So the only culprit what i anticipate is the JS running behind to render all the data. But i dont know how to trace or do performance analysis of JS on mobile. Any idea??
I'm not sure if this is what you're looking for, (your question somewhat confuses me) but here's how to test how long a piece of code takes in JavaScript:
var start = new Date().getTime(); //milliseconds
// your section of code
// ...
var elapsed = new Date().getTime() - start;
You could do that to test specific sections of your code for execution length.
If you had <div id="timetaken"></div> somewhere in your HTML, you could add
document.getElementById('timetaken').innerHTML="Time taken: " + elapsed;
And then when your code completes it would display how long that bit of code took to complete in your HTML so that you can see it on a mobile device.

iOS 5 Safari JavaScript execution exceeded timeout

I am working on a mobile web app that is primarily self-contained and communicated with the server only when necessary. Currently, the libraries being used are:
jQuery 1.6.4
jQuery UI 1.8.3
Modified/patched version of jQTouch
Up until the release of iOS 5 we were also using touchscroll.js but it is no longer needed since Safari now supports position: fixed and native scrolling.
Since the release of iOS 5, seemingly at random, this exception is raised:
JavaScript: Error undefined JavaScript execution exceeded timeout
Once it is raised, no JS code that runs for more than a very short period of time (say 1ms) will be executed by Safari. Refreshing the page, going to a new page, or going to a new domain has no effect. Any and all JS code, even something as simple as
for(var i = 0; i < 30; i++) ;
will not be executed by the browser without the exception being raised. The only way around this is to force kill Safari and restart it. I suppose it is also possible to wrap any remotely "heavy duty" code in the application in a window.setTimeout(..., 1) or take advantage of Web Workers for everything but UI updates but that doesn't seem like a very good solution as the application is fairly large and it would require a substantial rewrite.
Has anyone encountered this issue before? How would you go about debugging something like this as it isn't any single piece of code that seems to put Safari into this broken state and it can happen seemingly at random?
I tried to figure out what the timeout of the JS engine is in mobile Safari by doing the following:
var start, end;
start = new Date();
try {
while(true);
} catch (ex) {
alert('test');
}
end = new Date();
console.log(Number(end) - Number(start) + 'ms');
Unfortunately it seems this timeout exception isn't a JS exception so it cannot be caught in a try/catch block; however, it appears the max timeout period is in the realm of several seconds. None of the code in our app locks the browser/JS engine for that long (as it would provide a terrible UX) and most if not all of it probably has a sub 300ms execution time (including anything that's "heavy duty").
Are you using watchPosition? see this answer if so: JavaScript execution exceeded timeout
I've been ripping my hair out over this issue ever since iOS 5 was released - I feel your pain!

Javascript debugging

I have recently started to tinker with Project Euler problems and I try to solve them in Javascript. Doing this I tend to produce many endless loops, and now I'm wondering if there is any better way to terminate the script than killing the tab in Firefox or Chrome?
Also, is firebug still considered the "best" debugger (myself I can't see much difference between firebug and web dev tool in safari/chrome ).
Any how have a nice Sunday!
Firebug is still my personal tool of choice.
As for a way of killing your endless loops. Some browsers will prevent this from happening altogether. However, I still prefer just going ctrl + w, but this still closes the tab.
Some of the other alternatives you can look into:
Opera : Dragonfly
Safari / Chrome : Web Inspector
Although, Opera has a nice set of developer tools which I have found pretty useful. (Tools->Advanced->Developer Tools)
If you don't want to put in code to explicitly exit, try using a conditional breakpoint. If you open Firebug's script console and right-click in the gutter next to the code, it will insert a breakpoint and offer you an option to trigger the breakpoint meets some condition. For example, if your code were this:
var intMaxIterations = 10000;
var go = function() {
while(intMaxInterations > 0) {
/*DO SOMETHING*/
intMaxIterations--;
}
};
... you could either wait for all 10,000 iterations of the loop to finish, or you could put a conditional breakpoint somewhere inside the loop and specify the condition intMaxIterations < 9000. This will allow the code inside the loop to run 1000 times (well, actually 1001 times). At that point, if you wish, you can refresh the page.
But once the script goes into an endless loop (either by mistake or design), there's not a lot you can do that I know of to stop it from continuing if you haven't prepared for this. That's usually why when I'm doing anything heavily recursive, I'll place a limit to the number of times a specific block of code can be run. There are lots of ways to do this. If you consider the behaviour to be an actual error, consider throwing it. E.g.
var intMaxIterations = 10000;
var go = function() {
while(true) {
/*DO SOMETHING*/
intMaxIterations--;
if (intMaxIterations < 0) {
throw "Too many iterations. Halting";
}
}
};
Edit:
It just occurred to me that because you are the only person using this script, web workers are the ideal solution.
The basic problem you're seeing is that when JS goes into an endless loop, it blocks the browser, leaving it unresponsive to any events that you would normally use to stop the execution. Web workers are still just as fast, but they leave your browser unburdened and events fire normally. The idea is that you pass off your high-demand tasks (in this case, your Euler problem algorithm) to a web worker JS file, which executes in its own thread and consumes CPU resources only when they are not needed by the main browser. The net result is that your CPU still spikes like it does now, but your browser stays fast and responsive.
It is a bit of a pest setting up a web worker the first time, but in this case you only have to do it once. If your algorithm never returns, just hit a button and kill the worker thread. See Using Web Workers on MDC for more info.
While having Firebug or the webkit debuggers is nice, a browser otherwise seems like overhead for Project Euler stuff. Why not use a runtime like Rhino or V8?

Categories

Resources