Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 8 years ago.
Improve this question
I would like to avoid unresponsive javascript in all browsers.
Is it possible to write code with that in mind?
DETAILS: Problem is that currently there is a potential script block that executes fine in Chrome on my PC, but causing problems on IE (various versions). The worst thing is that I really don't know for sure if it is that script block at all. I will rewrite and solve that. However, I would like to know what exactly I should be avoiding while coding. This...
http://www.sitepoint.com/javascript-execution-browser-limits/
...is an interesting read but it's too general.
EDIT: I'm using jQuery/jQueryUI as well.
EDIT 2: There are patterns/principles to use to avoid particular problems. E.g. singleton pattern, PRG pattern, DRY principle... and such. Is there something like that for this kind of problem?
I've run into problems like this before as well.
The thing to keep in mind as you code, is where does my code begin execution, and where does my code end execution. For all of the time between those two points, the browser's UI thread is blocked, and the browser makers have understandably developed counter measures.
As far as what to avoid, avoid long, continuous loops.
Here's an extreme example:
function howManyMultiplesOfFourBelow(foo) {
var i = 0, j = 0;
while (i < foo) {
i++;
if (i % 4 === 0) {
j++;
}
}
return j;
}
If you pass 10,000,000 to that function, IE will definitely throw a fit. There is more than one way to program around this kind of situation; what I prefer is to break up the code using setTimeout/setInterval. After setting an interval and returning out of a function, we release the UI thread back to the browser, and the browser is in charge of executing the interval as often as we've requested (or as often as it is able).
I combine this with Futures/Promises; In particular, jQuery's implementation.
Using this style, the above example could be rewritten not to block the UI thread during the calculation by leveraging promises, and setInterval.
function howManyMultiplesOfFourBelow(foo) {
var deferred = $.Deferred(),
interval,
i = 0,
j = 0;
interval = setInterval(function () {
if (i >= foo) {
clearInterval(interval);
deferred.resolve(j);
return;
}
i++;
if (i % 4 === 0) {
j++;
}
}, 1);
return deferred.promise();
}
The first important difference is that this function no longer returns the answer, but instead a promise of an answer. So, consuming code might look like this:
howManyMultiplesOfFourBelow(10000000).done(function (multiples) {
//Update the DOM with the answer (multiples)
});
Returning to your question more generally, think about how much of your code must be run continuously, and if any of it could be delayed, or broken up in order to release the UI thread briefly.
Related
I am working on a question for my Computer Programming class in high school and the question is as follows.
Using a conditional statement, generate a program in any coding language and explain the working of it: “If the temperature of your room is more than 80° or less than or equal to 60°, then the program should branch; otherwise, the execution should continue without branching.”
I have managed to create a conditional statement on my own, but I do not understand the branching part. I have Googled already and have found nothing useful. Can someone explain what I am supposed to do?
**Also, I chose JavaScript for my coding language.
function temperature(z) {
if(z > 80 || z <= 60) {
/*branch program?*/;
}
else {
/*do not branch program?*/;
}
}
console.log(temperature(81)); /*evaluates to branching*/
That is all I have so far. Also, is there a simpler way to write that code? I would love some opinions!
The if statement itself is a branching instruction to your CPU where in assembly language CPU would’ve taken that instruction as a possibility to skip set of instructions inside the if statement and continue after it (branching) or execute that piece of code within the normal flow.
I believe that the statement you wrote is already a perfect example of the question, you should just be able to change some variable inside that if where that exact variable would’ve taken different value if the program were to take different execution path (aka branch).
Edit:
You could end up with code looking something like this:
function getTemperatureFeel(t) {
var feel = "Perfect"; // this is straight execution
if (t > 80 || t <= 60) {
feel = "Either warm or cold"; // this is branch execution
}
return feel;
}
console.log(getTemperatureFeel(81));
I am trying to create a loading bar during a very intensive period of JavaScript where some pretty heavy 3d arrays are built and filled. This loading bar needs to remain empty until the user clicks a button.
The freezing occurs whether or not I'm using -webkit-transition (This app can be chrome exclusive, cross browser is not necessary in my case).
Seeking simplicity I've built my bar like this...
<div id="loader">
<div id="thumb">
</div>
</div>
... and then sought to increment that bar at various stages of my main for loop:
for(i = 0; i < 5 ; i++){
document.getElementById('thumb').style.width = i*25 + '%';
//More Code
}
Problem is that everything freezes until the JavaScript finishes.
I found a similar question on Stack Overflow, Using CSS animation while javascript computes, and in the comments found and considered and/or tried the following:
Web Workers
Don't think it'll work since my script is filling an array with objects and constructors containing functions which according to this site isn't going to work
jQuery
Not an option, I can't use external libraries in my app - in any case, importing a whole library just for a loading bar seems kind of like overkill...
Keyframes
This was promising and I tried it, but in the end it freezes also, so no joy
timeOut()s
Thought about this, but since the point of the loading bar is to reduce frustration, increasing the waiting time seems counter-productive
I'd be happy to have any incrementation of the bar at this stage, even if it's not smooth! I'm pretty sure this is a problem that has struck more than just me - maybe someone has an interesting solution?
P.S.: I'm posting this as a new question rather than adding to the referenced question since I'm specifically seeking help with JavaScript (not jQuery) and would prefer if I could get it using a transition (!=animation) on the width.
Some people already mentioned that you should use timeouts. That's the appropriate approach, bc it'll give the browser time to "breathe" and render your progress bar mid-task.
You have to split your code up to work asynchronously. Say you currently have something like this:
function doAllTheWork() {
for(var i = 0; i < reallyBigNumberOfIterations; i++) {
processorIntensiveTask(i);
}
}
Then you need to turn it into something like this:
var i = 0;
function doSomeWork() {
var startTime = Date.now();
while(i < reallyBigNumberOfIterations && (Date.now() - startTime) < 30) {
processorIntensiveTask(i);
i++;
}
if(i < reallyBigNumberOfIterations) {
// Here you update the progress bar
incrementBar(i / reallyBigNumberOfIterations);
// Schedule a timeout to continue working on the heavy task
setTimeout(doSomeWork, 50);
}
else {
taskFinished();
}
}
function incrementBar(fraction) {
console.log(Math.round(fraction * 100) + ' percent done');
}
function taskFinished() { console.log('Done!'); }
doSomeWork();
Note the expression (Date.now() - startTime) < 30. That means the loop will get as much done as it can in the span of 30 milliseconds. You can make this number bigger, but anything over 100ms (essentially 10 frames-per-second) is going to start feeling sluggish from the user's point of view.
It may be true that the overall task is going to take somewhat longer using this approach as opposed to the synchronous version. However, from the user's experience, having an indication that something is happening is better than waiting indefinitely while nothing seems to be happening – even if the latter wait time is shorter.
Have you tried going even simpler and making a function, let's say:
Pseudo:
Function increment_bar(amount = 10)
{
document.getElementById('thumb').style.width = i*amount + '%';
}
Then from wherever you are doing your processing work just calling that function every x seconds or whenever you hit a certain point in processing (let's say 10-20% completion?)
Pseudo:
{
Doing_work_here;
increment_bar(25);
LOOP
}
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 11 years ago.
Improve this question
I have a massive collection of methods that I want to shape into a library. How do I begin the process?
Here is the begnning of the consolidation effort: I'm trying to decide if I should do this for my whole code base — move similar items into JavaScript objects.
Below is the consolidation effort followed by the whole code base:
Should I shape my code this way?
Consolidation Effort:
var menu = {
menu_timer:0,
menu_element:0,
/* called when mousing over the top menu item */
top_mouse_over: function (id)
{
menu.bottom_mouse_over();
menu.menu_element=document.getElementById(id);
menu.menu_element.style.visibility='visible';
},
/* hide the menu when the timer runs out */
hide_menu: function()
{
if(menu.menu_element)menu.menu_element.style.visibility='hidden';
},
/* keeps the menu open by clearing the timer when mousing over the menu items */
bottom_mouse_over: function()
{
if(menu.menu_timer)
{
window.clearTimeout(menu.menu_timer);}
},
/* set the timer to hide the menu, required by clearTimeout */
mouse_out: function()
{
menu.menu_timer=window.setTimeout(menu.hide_menu, 1000);
}
};
Entire Code Base:
Moved to codereview
First, refactor.
There no reason for a function called 16 or m6.
A few suggestions:
Use jQuery, Dojo, Zepto or any other library for your AJAX calls and mouse/keyboard events. There's no reason to reinvent the wheel. You now need to test your AJAX functions on every browser in the world. jQuery's AJAX function has already been tested.
try to use prettyDate instead of view_date.
Why do you minimize function names? What's the reason? Compressors can do this for you. Seriously, how can you work with this:
function m2(a,b) {
return document.getElementById(a).innerHTML=b;
}
Look into template functions (such as _.template, jQuery.template, mustache, etc). Look into validation plugins that might make your work easier.
You have 800 lines of code. You can make this to 200 readable lines of code.
Regarding making it a library: depending on the context I usually make it a jQuery plugin or using _.extend. Namespacing it to var menu = {} is sufficient though I'd pick a more relevant name than menu.
Your new approach is certainly an improvement. You should feel free to have your own style, but I would consider taking a conventional approach around documentation generation. In addition, if you take advantage of a library such as jQuery or Prototype, you'll be able to adapt from their style, instead of inventing your own. (I promise it won't stifle your creativity.)
Finally, you may consider pseudo-namespacing your object with a name that's less likely to be overridden in global. "window.menu" strikes me as slightly dangerous. Brand your core object while you namespace it.
Read up on Paul Irish's (Google Chrome, jQuery) method of kick-starting page-specific code.
http://paulirish.com/2009/markup-based-unobtrusive-comprehensive-dom-ready-execution/
I'm working on comparison for several different methods of implementing (real or fake) multithreading in JavaScript. As far as I know only webworkers and Google Gears WorkerPool can give you real threads (ie. spread across multiple processors with real parallel execution). I've found the following methods:
switch between tasks using yield()
use setInterval() (or other non-blocking function) with threads waiting one for another
use Google Gears WorkerPool threads (with a plugin)
use html5 web workers
I read related questions and found several variations of the above methods, but most of those questions are old, so there might be a few new ideas.
I'm wondering - how else can you achieve multithreading in JavaScript? Any other important methods?
UPDATE: As pointed out in comments what I really meant was concurrency.
UPDATE 2: I found information that Silverlight + JScript supports multithreading, but I'm unable to verify this.
UPDATE 3: Google deprecated Gears: http://code.google.com/apis/gears/api_workerpool.html
Web Workers. They’re a W3C standard (well, a working draft at the moment) for exactly this, and require no plugins:
This specification defines an API that allows Web application authors to spawn background workers running scripts in parallel to their main page.
The specification also discusses spreading workers across multiple cores, for true concurrency (this is handled invisibly by the browser’s JavaScript engine):
With multicore CPUs becoming prevalent, one way to obtain better performance is to split computationally expensive tasks amongst multiple workers. In [one] example, a computationally expensive task that is to be performed for every number from 1 to 10,000,000 is farmed out to ten subworkers.
yield() and setInterval() only schedule things to happen later, they don’t run concurrently with anything else.
I'm wondering - how else can you achieve multithreading in JavaScript? Any other important methods?
You can have your code transformed into JavaScript code that doesn't have any explicit loops or direct function calls, instead code is divided into small units of execution that are managed by a threading engine. In my example code I show how a function with loops would be transformed but I've omitted the mechanism for function calls just to keep the example simple.
The process of transformation basically works by splitting code at division points. These division points are function calls and loops (as demonstrated above). In the example I've used objects and keys but it may be much easier on the browser's JavaScript engines if the units stored the stack as an object variable (i.e. storing using this.foo = bar instead of stack["foo"] = bar).
For example the following code:
// Phoney method purely to demonstrate structure
function Foo() {
var i,
sum = 0,
accumulator_list = [],
accumulator_modulus = [],
kMaxAccumulatorCount = 100;
// Calculate accumulations
for(i = 0; i < kMaxAccumulatorCount; ++i) {
current_accumulator = GetNextAccumulator()
accumulator_list[i] = current_accumulator;
sum = sum + current_accumulator;
}
// Calculate accumulator modulus
for(i = 0; i < kMaxAccumulatorCount; ++i) {
current_accumulator = accumulator_list[i];
accumulator_modulus[i] = current_accumulator % kMaxAccumulatorCount;
}
}
... into something like this:
function Foo_A(caller,stack) {
var stack = {};
stack["i"] = undefined;
stack["sum"] = 0;
stack["accumulator_list"] = [];
stack["accumulator_modulus"] = [];
stack["kMaxAccumulatorCount"] = 100;
stack["i"] = 0;
return {caller: caller, stack: stack, next=Foo_B};
}
function Foo_B(caller, stack) {
stack["current_accumulator"] = GetNextAccumulator();
stack["accumulator_list"][stack["i"]] = stack["current_accumulator"];
stack["sum"] = stack["sum"] + stack["current_accumulator"];
// For-loop condition satisfied ?
if(stack["i"] < stack["kMaxAccumulatorCount"]) {
++stack["i"];
return {caller: caller, stack: stack, next:Foo_B};
} else {
// Initialise the next for loop.
stack["i"] = 0;
return {caller: caller, stack: stack, next:Foo_C};
}
}
function Foo_C(caller, stack) {
stack["current_accumulator"] = stack["current_accumulator"][stack["i"]];
stack["accumulator_modulus"][stack["i"]] = stack["current_accumulator"] % stack["kMaxAccumulatorCount"];
// For-loop condition satisfied ?
if(stack["i"] < stack["kMaxAccumulatorCount"]) {
++stack["i"];
return {caller: caller, stack: stack, next:Foo_C};
} else {
// Function has finished so the next will be null. When the thread-engine sees this it simulates the behaviour of a return, pops its virtual stack and returns execution to the caller
return {caller: caller, stack: stack, next:null};
}
}
Multithread.js is a library for really easy multithreading in JS that wraps Web Workers and does the majority of your work for you. :)
q: how else can you achieve concurrency in Javascript
You can use async or 'non-blocking' type methods. This has one of the major buzzes about the node.js system.
It's not exactly multithreaded, but it does tend to be faster.
There is no direct support for multithreading in JavaScript. However you can achieve this by applying some ideas and method.
There are methods like:
var id = window.timeout("javascript code", time);
here the JavaScript code is called after the specifed time and we can use
window.clearTimeout(id);
for clearing.
By this we can achieve fake concurrency.
I am finally getting around to really implementing some jQuery solutions for my apps (which is seeming to also involve a crash course in javascript).
In studying examples of plugins, I ran across this code. I'm assuming the author created the zero length timer to create some seperation of the running code, so that the init functon would finish quickly.
function hovertipInit() {
var hovertipConfig = {'attribute':'hovertip',
'showDelay': 300,
'hideDelay': 700};
var hovertipSelect = 'div.hovertip';
window.setTimeout(function() {
$(hovertipSelect).hovertipActivate(hovertipConfig,
targetSelectById,
hovertipPrepare,
hovertipTargetPrepare);
}, 0);
}
Is needing this type of seperation common?
Is creating the zero length timer still the best way to handle this situation, or is there a better to to handle this in jQuery?
Thanks,
Jim
Check out this article that explains when this is necessary.
Also check out this related question.
It is not very common, but is necessary when you need to escape the call stack of an event.