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/
Related
Essentially I have some custom controls like sliders and dropdown menus with cool effects.
They rely heavily on getBoundingClientRect to allow for flexibility in CSS, things like changing paddings/font sizes/whatever without throwing off how the control works.
The downside is, getBoundingClientRect is a bit expensive to call so often and due to the way the code is laid out, it sometimes gets called multiple times for the same element in the same frame.
Now I could try and call it only once for each element but it would be a pile of messy if-then sphagetti. Alternatively, I figured I could store the value on a global frame # basis.
Is there a global document frame # available in js?
The question is still open but I found a way to implement my own frame counter
window.render_stats = {
"total_frames" : 0,
};
(function() {
render_stats.total_frames += 1;
requestAnimationFrame(arguments.callee);
})();
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.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I have a loop that looks like this:
$('#SomeSelectorID').find('.SomeElementsByClassName').each(function () {
$(this).some code here;
$(this).some other code there;
$(this).some other code here and there;
});
If I write at the top of the loop var TheThis = $(this); and then replace $(this) with TheThis is that a performance optimization or not really?
It's a definite performance optimisation. One you'll probably not notice, but that's no reason not to do it.
The code in your example means that the DOM will be interrogated 3 times to look for the $(this) element and then perform the actions on it. Caching it in a variable means that that will only occur once.
If you really want to see the difference try comparing your original with the below in a JSPerf test.
$('#SomeSelectorID').find('.SomeElementsByClassName').each(function () {
var $this = $(this);
$this.some code here;
$this.some other code there;
$this.some other code here and there;
});
Yes there is a performance penalty. I've created a small demo that illustrates using $(this) is slower than using a stored version of it.
JSFiddle demo here.
No I don't think you need to change your code. The benefit in this case will be so small that you will hardly notice any difference. Maybe in another situation where you are developing a game or data processing app it can matter.
Here are the results of my test...
Testing jquery version...
1000000 iterations $(this): 0.006849ms
Testing non-jquery version...
1000000 iterations of this$: 0.001356ms
Of course it is a performance optimization. Whether it is worth it or not, that's the real question. If you are reiterating over the DOM then it would definitely be worth it. In this case, you are just wrapping an object in jQuery so the footprint is much smaller.
That being said, you gain a little bit of performance but lose nothing in terms of readability, maintainability, or other things that you usually have to sacrifice to gain performance, so you may as well make the tweak.
Testing this shows no performance impact, at least on Chrome:
var start = new Date().getTime(),
iterations = 50000;
$('#foo').find('.bar').each(function () {
var that = $(this);
for(var i = 0; i < iterations; i++)
that.find('i');
});
console.log(new Date().getTime() - start);
Using $(this) results are more or less the same.
http://jsfiddle.net/BuREW/
Well, duh.
In general, calling any function is an expense. Calling $() is a HUGE one (compare calling times compared to Vanilla JS) and one that should be avoided as much as possible.
Storing its return value in a variable is always a good thing, but it also avoids certain "gotchas".
For instance, let's say you want to change all .test elements to green and remove the class. You might do this:
$(".test").removeClass("test");
$(".test").css({"color":"green"});
Only to find that it doesn't change the colour to green because $(".test") isn't the same thing anymore.
Conversely, if you had done:
var test = $(".test");
test.removeClass("test");
test.css({"color":"green"});
It works. Of course, this is a trivial example since you can just rearrange the code lines and it works too, but I'm triyng to make a point here :p
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 9 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
I've been looking around for a decent jQuery plugin that can handle both dates and times. The core UI DatePicker is great, but unfortunately I need to be able to take time in as well.
I've found a few hacks for the DatePicker to work with times, but they all seem pretty inelegant and Google isn't turning up anything nice.
Is there a good jQuery plugin for selecting dates and times in a single UI control with a usable interface?
By far the nicest and simplest DateTime picker option is http://trentrichardson.com/examples/timepicker/.
It is an extension of the jQuery UI Datepicker so it will support the same themes as well it works very much the same way, similar syntax, etc. This should be packaged with the jQuery UI imo.
#David, thanks for the recommendation! #fluid_chelsea, I've just released Any+Time(TM) version 3.x which uses jQuery instead of Prototype and has a much-improved interface, so I hope it now meets your needs:
http://www.ama3.com/anytime/
Any problems, please let me know via the comment link on my website!
In my view, dates and times should be handled as two separate input boxes for it to be most usable and efficient for the user to input. Let the user input one thing at a time is a good principle, imho.
I use the core UI DatePicker, and the following time picker.
This one is inspired by the one Google Calendar uses:
jQuery timePicker:
examples: http://labs.perifer.se/timedatepicker/
project on github: https://github.com/perifer/timePicker
I found it to be the best among all of the alternatives. User can input fast, it looks clean, is simple, and allows user to input specific times down to the minute.
PS:
In my view: sliders (used by some alternative time pickers) take too many clicks and require mouse precision from the user (which makes input slower).
My best experience with a datepicker is with the prototype-based AnyTime. I know that's not jQuery, but it may still be worth the compromise for you. I know absolutely no prototype, and it's still easy enough to work with.
One caveat I've found: it is not forward compatible on some browsers. That is, it did not work with a newer version of prototype on Chrome.
Just to add to the info here, The Fluid Project has a nice wiki write-up overviewing a large number of date and/or time pickers here.
I researched this just recently and have yet to find a decent date picker that also includes a decent time picker. What I ended up using was eyecon's awesome DatePicker, with two simple dropdowns for time. I was tempted to use Timepickr.js though, looks like a really nice approach.
I have ran into that same problem. I actually developed my using server side programming, but I did a quick search to try and help you out and found this.
Seems alright, didn't look at the source too much, but seems to be purely JavaScript.
Take look:
http://www.rainforestnet.com/datetimepicker/datetimepicker.htm
Here is the demo page link:
http://www.rainforestnet.com/datetimepicker/datetimepicker-demo.htm
good luck
This is some code I use to have a user select one
datetimepicker, set the datetime, and have the
other datetimepicker add One Minute to that time.
I needed this for a custom medication control....
Anyway, thought it might help someone else since I could
not find the answer any where online...
(at least not a complete answer)
Keep in mind that the 60000 added, adds one minute.
(60 * 1000 milliseconds)
$('.frdtPicker').datetimepicker({
onClose: function(dateText, inst) {
var endDateTextBox = $('.todtPicker');
if (endDateTextBox.val() != '') {
var testStartDate = new Date(dateText);
var testEndDate = new Date(endDateTextBox.val());
if (testStartDate > testEndDate) {
var testStartDate = new Date(dateText).getTime() + 60000;
var testStartDate2 = new Date(testStartDate);
endDateTextBox.datetimepicker('setDate', (new Date(testStartDate2)));
}
}
else {
var testStartDate = new Date(dateText).getTime() + 60000;
var testStartDate2 = new Date(testStartDate);
endDateTextBox.datetimepicker('setDate', (new Date(testStartDate2)));
}
$('.frdtPicker').val(dateText); //endDateTextBox.val());
},
onSelect: function(selectedDateTime) {
var start = $(this).datetimepicker('getDate');
$('.todtPicker').datetimepicker('option', 'minDate', new Date(start.getTime()));
}
});
Take a look at the following JavaScript plugin.
Javascript Calendar with date and time
I've made it to be simple as possible. but it still in its early days.
Let me know the feedback so I could improve it.
Not jQuery, but it works well for a calendar with time: JavaScript Date Time Picker.
I just bound the click event to pop it up:
$(".arrival-date").click(function() {
NewCssCal($(this).attr('id'), 'mmddyyyy', 'dropdown', true, 12);
});
I make one function like this:
function getTime()
{
var date_obj = new Date();
var date_obj_hours = date_obj.getHours();
var date_obj_mins = date_obj.getMinutes();
var date_obj_second = date_obj.getSeconds();
var date_obj_time = "'"+date_obj_hours+":"+date_obj_mins+":"+date_obj_second+"'";
return date_obj_time;
}
Then I use the jQuery UI datepicker like this:
$("#selector").datepicker( "option", "dateFormat", "yy-mm-dd "+getTime()+"" );
So, I get the value like this: 2010-10-31 12:41:57
We had trouble finding one that worked the way we wanted it to so I wrote one. I maintain the source and fix bugs as they arise plus provide free support.
http://www.yart.com.au/Resources/Programming/ASP-NET-JQuery-Date-Time-Control.aspx
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.