Is having too many setTimeout()s good? - javascript

I'm using mostly Javascript on my scripting. I have some scripts which do several tasks every 1 second, and some every 0.02 seconds, etc. My intervals do tasks like checking of ifs, doing some innerHTML, little animation, etc. Now I have 4, but I think it would increase in the future; maybe I'll control myself to less than 10. Though it doesn't lag at all in my computer.
Generally, will it be good for a site?
Since it's client-side obviously there won't be any issues with internet connection, right?
Is it a bad practice, or is it not much of an issue at all?
Also, I have a question for jQuery. There are things that normal Javascript and jQuery can do similarly (like innerHTML and .html()), right? Given this situation, which should I prefer to use, jQuery or Javascript?
Thank you.

Is having too many setTimeout()s good?: You already gave your self the answer too many is not good, no matter what you talk about.
Generally will it be good for the site: Probably not, remember you don't know the cpu/browser combo of your users, so you should build your site so it will still be nice to use for people who have slower computers than you. A laggy/unresponsive site is the first one users will flee from.
Since it's client-side obviously there won't be any issues with internet connection, right? right, unless you do network requests as part of the timeouts. Ajax calls every second is rarely a good idea.
Is it a bad practice, or is it not much of an issue at all? poor architecture is bad practice. If you wish to follow the best practices, read up on design patterns.
Also, I have a question for jQuery. There are things that normal Javascript and jQuery can do similarly (like innerHTML and .html()), right? Given this situation, which should I prefer to use, jQuery or Javascript? Using jQuery gives you convinient crossbrowser compatibility. In most cases for non-experts using a library like jQuery is better than not using it.

Generally, will it be good for a site?
Most of the other answerers are saying no, but they can't possibly make this claim without more information. This decision is specific to your site. It might be perfectly fine. Don't make guesses about performance. Measure things. Fix performance issues where they really exist, not where your gut tells you they exist.
Since it's client-side obviously there won't be any issues with internet connection, right?
Correct.
Is it a bad practice, or is it not much of an issue at all?
There are lots of tasks that are best performed with a timeout callback. If you need to do something periodically, or after a certain amount of time has passed, then setTimeout is not only reasonable to use, it's specifically designed for those tasks.

For your first question, it's more a case of what you're doing in each callback that gets called after the timeout. Without knowing that it's hard to provide a clearer answer.
But remember that javascript is single threaded in the browser, so if you're running expensive operations regularly it's not going to work well. If you're looking to do animations with this, I'd strongly urge you to consider one of the existing libraries first (dojo, jquery, mootools etc) and only try and implement this yourself if you find them insufficient. A lot of work has gone into making those libraries performant and it's unlikely you'll do better on a first stab.
Second question: Again, I'd use the library. For a simple innerHTML there's unlikely to be much difference, but in the general case a library like jQuery or Dojo will help to cover over the differences between the DOMs in the different browsers, catch the nasty edge cases you don't know (or want to know) about and is likely to be better tested and supported than your own code. Get it working their way, then optimise with your own vanilla JS if/when you need to.

1) Generally good: no, in general it creates processor load, which slows down the browser. But that will be influenced more by the actual code than the timeouts itself. But modern day browser don't have any problems with 10 timers... ;)
2) Yeah, no problem with the timeout.
3) No, it's the only way to do asynchronous processing. so it isn't really an issue ;)
4) The difference with innerHTML and .html() (and other jQuery functions) is that jQuery has better cross-browser implementations. It knows the quirks of certain browsers and is able to circumvent them. For simple problems plain 'ol JavaScript is perfect (and is cheaper in bandwidth and processing power). But for more complex scripts, and once you have chosen to use jQuery, why not use it anyway. ;)

Go with Jquery - Write Less, Do More
You can have so many functions , effects , plugins will help you to save time from coding.
Any way when you are developing a website with javascript or jquery effects , you will be expecting the user should have an updated browser and system.
your functionality not gonna work on ie 5 . :)
So adding time out and js functions will not affect performance as per my understanding.
http://api.jquery.com/delay/
http://api.jquery.com/toggle/
http://api.jquery.com/html/
Go with jquery api functions and develop your own..instead of usng plugins.

Related

Removing jQuery for performance reasons justified?

I am on a new project and our job is to rewrite an e-commerce website that is having performance problems on mobile devices.
We are re-writing the javascript based on a more object-oriented/modular architecture which I think is great! However my team lead said that we should remove all the jQuery calls and replace with javascript like so domElem.querySelectorAll(query) , which has better performance. I understand jQuery does some kind of caching in the background which can create memory issues.
I am a little sceptical of this, firstly because it seems like a case of 'premature optimization', that is, we should find the bottle-necks first before we re-write anything. And secondly I haven't found anything on the internet that says that jQuery has significant performance problems.
The current website does have a lot of overlapping dom branch queries which I think creates a lot of redundancy. That is there is too much querying happening, and on our new architectual approach we are restricting our object/module to fewer dom queries and more targeted dom queries which is great. This does need to be re-written.
But whether or not we use domElem.querySelector(query) or $(domElem).find(query), I can't see there as being much of a difference. Is my thinking right?
Some tests are done here (check other revisions as well). Good detailed discussion is done here over pros and cons of using jquery over javascript.
Also want to point out that jquery doesn't do any caching of selectors.
The thing we often forget because of using Javascript frameworks all the time is that jQuery is not a framework.
Obviously, if you do the exact same one-operator action using the jQuery '$' object and using a direct DOM method like getElementById, the latter will be noticeably faster as jQuery itself is written in Javascript and does a lot of background stuff.
However, nothing (except code readability) prevents you, as a developer, from combining jQuery with plain Javascript: using plain Javascript wherever possible and only using jQuery functions that provide complex functionality and take some time to write and optimize from scratch. There are a lot of those in jQuery: providing browser-independent css, serializing object and doing lots of other cool stuff.
It depends on the application but usually performance troubles are related to badly-designed algorithms, not the use of jQuery.
In any case, if your application does a lot of DOM-manipulation, it may be worthwhile to re-write it using plain Javascript and test. Keep the library, just don't use it for simple operations you can easily write without it.
If your application is heavily-reliant on jQuery functions with complex functionality, removing it is out of the question.
I myself use this combined approach: everything simple written in Javascript with jQuery functions for stuff that is difficult to implement.
Also, a good place to dig around if the app has troubles with performance is the DOM-manipulation. Those operations are very heavy compared to almost everything else in Javascript. You may be able to cut down on time by rolling several operations into one, building finished objects with one constructor, instead of creating empty ones and assigning properties one-by-one, etc.
Sorry, if the answer is a bit vague but it's difficult to be precise in this case without seeing the code and running tests.
Let me quote Uncle Bob about this discussion "Architecture is about intent, we have made it about frameworks and details"
Premature optimizations needs to be considered carefully.
They often result architectural decisions that are not easily revertible.
They introduce code optimizations that are usually specific to the problems they solve, which makes the code less abstract thus hard to
maintain, and more complicated thus prone to more bugs.
They tend to be prejudice and not objective, sometimes without any real comparison to other alternatives.
The problems they are trying to solve tends to be overestimated, to the degree of non-existent.
I'm not a big expert on Web development but if possible, you should always push this kind of decisions to the end by separation of concerns, and good abstraction.
For example over the parts that generate the java-script code you can have an abstraction of JavaScriptWriter, and use different frameworks. This way you can use JQuery at the beginning, test the system and only then replace parts you know to be inefficient.

jQuery vs. javascript? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I recently stumbled upon some javascript forums (sadly, link is lost somewhere in the universe), where you could feel real hate against jQuery for not being... any good?
Most arguments seem to make sense actually.
Now, I really like jQuery, mostly for letting me concentrate on things I want to do rather on browser inconsistencies and it actually makes AJAXing with cool (or overused?) effects fun.
But if really is something rotten in the core of jQuery, I don't want to rely on it the way I actually... rely on it.
I don't want to start yet another argument over which framework is the best... but... Which framework is the best (joke)? As a case usage, think about small to medium web and it's administration.
I'm just trying to figure out, if stuff in some framework or pure javascript with few mine functions really makes difference.
Edit:
I actually tried to have a normal objective discusssion over pros and cons of:
Using a framework over pure javascript and
jQuery vs. others,
Since jQuery seems to be easiest to work with with the quickest learning curve. However, some people just don't understand it and think that I'm starting yet another flame (what I am not). I am actually voting to reopen this question.
Also I'm really interested in:
Does jQuery heavily rely on browser sniffing? Could that be a potential problem in the future? Why?
I found plenty JS-selector engines, are there any AJAX and FX libraries?
Is there any reason (besides browser sniffing and personal "hate" against John Resig) why jQuery is wrong?
jQuery actually, as most used, stands for other frameworks also.
It's all about performance and development speed. Of course, if you are a good programmer and design something that is really tailored to your needs, you might achieve better performance than if you had used a Javascript framework. But do you have the time to do it all by yourself?
My personal opinion is that Javascript is incredibly useful and overused, but that if you really need it, a framework is the way to go.
Now comes the choice of the framework. For what benchmarks are worth, you can find one at http://ejohn.org/files/142/ . It also depends on which plugins are available and what you intend to do with them. I started using jQuery because it seemed to be maintained and well featured, even though it wasn't the fastest at that moment. I do not regret it but I didn't test anything else since then.
Personally i think you should learn the hard way first. It will make you a better programmer and you will be able to solve that one of a kind issue when it comes up. After you can do it with pure JavaScript then using jQuery to speed up development is just an added bonus.
If you can do it the hard way then you can do it the easy way, it doesn't work the other way around. That applies to any programming paradigm.
jQuery like any other good JavaScript frameworks supplies you with functionality independent of browser platform wrapping all the intricacies, which you may not care about or don't want to care about.
I think using a framework is better instead of using pure JavaScript and doing all the stuff from scratch, unless you usage is very limited.
I definitely recommend jQuery!
"I actually tried to had a normal objective discusssion over pros and
cons of 1., using framework over pure javascript and 2., jquery vs.
others, since jQuery seems to be easiest to work with with quickest
learning curve."
Using any framework because you don't want to actually learn the underlying language is absolutely wrong not only for JavaScript, but for any other programming language.
"Is there any reason (besides browser sniffing and personal "hate"
against John Resig) why jQuery is wrong?"
Most of the hate agains it comes from the exaggerated fanboyism which pollutes forums with "use jQuery" as an answer for every single JavaScript question and the overuse which produces code in which simple statements such as declaring a variable are done through library calls.
Nevertheless, there are also some legit technical issues such as the shared guilt in producing illegible code and overhead. Of course those two are aggravated by the lack of developer proficiency rather than the library itself.
Does jQuery heavily rely on browser sniffing? Could be that potential problem in future?
Why?
No - there is the $.browser method, but it's deprecated and isn't used in the core.
I found plenty JS-selector engines, are there any AJAX and FX libraries?
Loads. jQuery is often chosen because it does AJAX and animations well, and is easily extensible. jQuery doesn't use it's own selector engine, it uses Sizzle, an incredibly fast selector engine.
Is there any reason (besides browser sniffing and personal "hate" against John Resig) why jQuery is wrong?
No - it's quick, relatively small and easy to extend.
For me personally it's nice to know that as browsers include more stuff (classlist API for example) that jQuery will update to include it, meaning that my code runs as fast as possible all the time.
Read through the source if you are interested, http://code.jquery.com/jquery-1.4.3.js - you'll see that features are added based on the best case first, and gradually backported to legacy browsers - for example, a section of the parseJSON method from 1.4.3:
return window.JSON && window.JSON.parse ?
window.JSON.parse( data ) :
(new Function("return " + data))();
As you can see, if window.JSON exists, the browser uses the native JSON parser, if not, then it avoids using eval (because otherwise minfiers won't minify this bit) and sets up a function that returns the data. This idea of assuming modern techniques first, then degrading to older methods is used throughout meaning that new browsers get to use all the whizz bang features without sacrificing legacy compatibility.
Jquery VS javascript, I am completely against the OP in this question. Comparison happens with two similar things, not in such case.
Jquery is Javascript. A javascript library to reduce vague coding, collection commonly used javascript functions which has proven to help in efficient and fast coding.
Javascript is the source, the actual scripts that browser responds to.

Using multiple Javascript frameworks in a project?

Is it good or okay to have several frameworks in a project, or is it bad because it gets cluttered (= a mess), and the loading times maybe get's longer. Does some 100 K matter really? Or should you stick with one?
It's generally better to pick one thing and stick with it, for a number of reasons:
Fewer dependencies.
Lower complexity.
Easier to maintain.
Faster loading times.
No likelihood of dependency conflicts (i.e. jQuery can't conflict with your other Javascript framework if you only have one).
Lower debugging times.
It's true that an extra ~50k these days probably isn't going to kill anybody for a personal site or blog. The benefit comes when you scale to larger sizes, and all those extra 50k hits are eating into your bottom line. But even if you're just doing this for a small site, the savings on your sanity from figuring out problems quicker will easily be worth it.
That said, if you just need one part of a specific piece of a Javascript framework, the larger ones are often split into logical chunks, so that you can just take the piece you need rather than the entire framework. Most are rich enough these days that if framework X has a feature you want, but you're using framework Y, you can pretty much just map the source code for that feature directly into framework Y.
If you can load the javascript library from a repository where it would be cached on the first visit, then i don't really see any problem with that.
But, for uniformity sake i will go with one javascript library.
But, if you really have any strong reason to use two, then go ahead. As far as it is cached the first time.
Just adding something to John's words, one could choose, for example, JQuery, which allows you to use it without clashing with other libraries. I remember that once, I had troubles while trying prototype and mootools because I wanted some things from the former and some other from the latter, but it was long ago and maybe it was solved.
Somehow, I've found that it's easier to maintain a single library and there're a few real differences between them. It related more to the way each one approaches to map documents and apply things to their elements, which causes differences in response time, but the goal happens to be the same.
Good luck with your choice :)
PS. If you gzip and fix etags in the stuff you offer in your webapps, the difference between loading one or two js frameworks is not reeeeaaally important -unless you're in facebook, meebo or so!-. I've found that the yahoo! recommendations are helpful.
http://developer.yahoo.com/performance/rules.html
I wouldn't run two frameworks unless there was really no alternative. They often aren't written to play well with others; there are lots of potential ways they can cause unwanted interactions.
For example with jQuery, a lot depends on the user-data key identifiers the library adds as attributes to element nodes. If you start messing with the structure of the document by cloning, adding/removing and so on from another framework (or even just plain DOM methods) then those identifiers aren't as unique as jQuery expects; it can easily get confused and end up failing to call event handlers, or tripping on errors. This sort of thing isn't fun to debug.

Why would I want to use jQuery? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
(I understand that someone else asked a similar question and it was closed as 'argumentative', but I'm really interested in understanding the arguments around this.)
I know JavaScript really well. I've been writing it professionally for years. I've internalized a lot of the cross-browser incompatibilities and sketchiness, know DOM manipulation like the back of my hand, have worked with some of the best web developers in the industry & picked up a lot of their mojo.
I've been checking out jQuery. I understand the point of a javascript library (how many times have I written animation, getElementsByClass, and hide/show functions?). But to be honest, it seems like a waste of time to learn an entirely new syntax that isn't less complex. It seems like I'd be bashing my head against a wall to learn an entirely new interface to the same old JavaScript.
I'm not technically an engineer, so maybe I'm missing something. Could someone spell out the tradeoffs of jQuery? Is it really faster to learn and understand jQuery syntax than to just learn JavaScript?
There are a few big benefits to using a framework over homegrown/handwritten code:
Abstractions. I'm sure you're very proud of the fact that you've slung enough JS to be able to write animations from scratch. You should be! However, abstracting common functionality away from yourself is actually very liberating. You just call the method and know the innards will be executed, and executed well. Even if you're very fast at writing the low-level stuff yourself, that's still time you've spent on that instead of solving today's problems.
Common language. Using a common framework is like speaking a common language. You can collaborate with other developers very easily, and each can pick up where others left off without friction. (Compared to stepping into an application which uses a homegrown library for the things jQuery can do.)
Experts. The people working on jQuery are JavaScript gods. I am really, really good at JavaScript, and you probably are too, but there's a big difference between normal good and jQuery good. A team of insanely good people are constantly poring over a small set of common functionality - tuning it, tweaking it, enhancing it to make it the best it can possibly be. That represents a huge number of man-hours a single person like you or me simply cannot reproduce, no matter how good we are. And if you are as good as the jQuery guys, you can only benefit by combining your talent with theirs and contributing to the jQuery codebase. It's a melting pot of insane talent.
I'm not technically an engineer, so maybe I'm missing something. Could someone spell out the tradeoffs of jQuery? Is it really faster to learn and understand jQuery syntax than to just learn JavaScript?
jQuery is more than "just another interface" to Javascript. It allows you to express yourself in ways that are more compact and succincter than the corresponding Javascript implementation. At the same time, it's clearer and much more powerful. Specifically, the benefits you get include:
Expressiveness. jQuery is essentially a DSL for DOM manipulation and querying. This specificity is a major source of its utility and effectiveness.
Cross-browser. To a very large extent, jQuery is "write once, run anywhere". Even in 2009, this is still a surprisingly rare feat for web-based platforms. It's gratifying and relieving to know that you won't have to waste time debugging obscure problems on IE6 (well, most of the time).
Highly complete documentation. As a developer, I prize APIs and frameworks that have taken the time to spell out what all the moving pieces are supposed to be doing. Nothing is more encouraging than knowing that (1) things are stable enough that writing documentation isn't an attempt to hit a moving target and (2) things are useful enough that they've attracted enough people to flesh out the documentation fully.
In sum, the difference between Javascript and jQuery is analogous to the difference between assembly and higher-order programming languages. Although they're both technically both "an interface to machine language" and can both do similar things, the latter is considered far more powerful because of how easy it is to represent things and develop rapidly.
One thing I don't see mentioned is that the library is written to work cross browser on a wide range of popular browsers and platforms: IE6+, Firefox 2+, Safari 3+
That alone is reason enough to use jQuery then to write your own JavaScript and have to worry about cross browser issues yourself.
You can't learn jQuery without learning JavaScript, and you can't be a jQuery guru without being a JavaScript guru.
That said, it really is much faster to do things with jQuery than with "bare metal" JavaScript. Moreover, the way one works with jQuery is at a far more abstract level than the way one works with "bare metal" JavaScript. In addition, the jQuery syntax is very basic and not at all hard to learn, although the way you think about jQuery is very different from the way you think about "bare metal" JavaScript but enables you do to much more, much more rapidly.
community support
other developers writting and testing code, make it possible for you to do things you simply do not have time to do. Its not about doing anything you do not know how to do, its about doing things quickly, efficiently, and of very high quality (its already been tested).
From the sounds of it, you know much of the same stuff that jQuery knows about the DOM, and I can only assume you've built-up a nice DOM toolset for yourself over the years that incorporates all of this knowledge. In short, No, you don't need to use jQuery. However, some of the rest of us do not know as much about the DOM, and jQuery levels the playing field so we can get on with getting work done for our clients.
That is not to say you should not learn jQuery (as opposed to using it). You may pickup a few things you didn't know. The 3 main features that distinguish it from other DOM libraries (including your own probably) are:
built-in support for CSS selector syntax, useful for finding elements
methods that operate on the set of wrapped elements
chaining. Every method in jQuery.prototype (with "setter" behaviour) returns this
Personally, 1) and 3) don't hold a high premium. But 2) turns out to be huge for me. I never realized until jQuery how much my code tended towards operating on a set of nodes rather than a single node (if someone would have asked me I would have guessed the opposite tendency). 2) virtually eliminated all for loops from my code (or .forEach or however else I tended to abstract it), which was actually quite liberating. Now I notice it's the rare occasion where my code must operate on some single element.
Speed of development and turnaround of code.
One thing I haven't seen mentioned in the other answers is that, eventually, someone else is going to have to maintain your code. If it's all custom, they'll have a rougher time of it than if a more standard library is used. If that's not of any concern to you, and you don't think you're likely to need any of the really slick jQuery modules, then keep on with what you're doing.
For me, there are several benefits, like speed of development, etc.
But at the end of the day, it boils down to one thing:
It removes a HUGE amount of the cross-browser BS that can eat up so much time and resources, so I don't have to deal with it
jQuery allows you to write shorter, cleaner code that's easy to understand. Many people use it, so there are many plugins that work along with it, minimizing bloat. The same may not be true of your own personal library.
If you know JavaScript really well you should also know that jQuery's syntax isn't different from JavaScript's syntax.
What you might be referring to is the chaining idiom (used everywhere in jQuery) which seems to make things look very different from other sort of code. Well there's a reason for that, it's because it bonds really well with how the DOM works.
If you truly know JavaScript, you'll be at running speed with jQuery in under a week's time. If you don't already know your way around JavaScript, adding a layer on top might do more harm than good. But that's just like anything else!
You're going to be writing better looking and easier to understand JavaScript at a faster pace and only once — not once per browser. Downside? You're going to tack on another ~50KB of JavaScript. That's what caching is for :)
Jquery is javaScript in the hand of the designer.
It is as easy as writing CSS styles on an element.
Also Jquery is the easiest to understand, write maintain, add plugins.
I was working on a gallery program for a client (which is now exhibiting inexplicable behavior in IE6 and 7 - surprise, surprise - but I found that when I switched from bare-metal Javascript to jQuery a lot of the work got much easier. To me, it makes available the CSS view of the DOM while writing Javascript - which makes traversal and manipulation much more intuitive. Also, the cross-browser compatibility and brevity is wonderful.
It doesn't really matter if jQuery is great or awful. It's the powerhouse JS library now, used on a huge number of pages, and future browsers will have to accommodate it or be seen as themselves buggy.
What I don't like about jQuery: I'm not that thrilled about how it ignores mobile phone browsers in its test suites. It gets pulled in on all kinds of pages on mobile phones, and yet it makes no effort to ensure it works well on them.
jQuery degrades gracefully and it's one of the fastest (not THE fastest anymore though):
http://mootools.net/slickspeed/
There are many other frameworks out there, and whichever you choose, you probably wouldn't go wrong, but having uses jQuery myself, I'd definitely recommend it.
:)

Is there a resource to help convert Prototype JavaScript to jQuery?

I have extensively used Prototype before and it helped us add considerable interactivity to our web applications. However we are looking at making the move to use jQuery in order to standardize on something better supported in Visual Studio.
I understand that we can use the jQuery.noConflict to run it alongside Prototype, but we would like to avoid having users need to download both libraries to use our website.
So, is there a good resource that can help us move old scripts from Prototype to jQuery?
I can't really help you too much with your question, other than to say that I haven't heard of any such tool, and that I'd be really surprised if one actually existed.
While I think jQuery is a great library, and that you're right to be wanting to only use one library, just remember that the cost of you changing over all your scripts is going to be many many hours of work. The cost of your users downloading an extra 30kb of scripts is going to be roughly 0.3 seconds. Perhaps try to slowly phase out Prototype and only refactor your existing pages when a) you have to, or b) if you've got nothing better to do.
Falkayn,
There is no automated process available for conversion of JavaScipt code written against one JS library to another one. Moreover there cannot be one. Different libraries implement different proramming models as well as they arrange their APIs in different manner.
So, before you have found a solution to your problem now ask yourself a question: Am I going to convert my jQuery code once another even "cooler" "X-type" JavaScript library became available?
If your answer is no, take your time and convert the code manually no mater how long will it take. In case you answer "yes" don't convert the code at all.
So it goes.
Thanks guys for your input. I was looking for more of a syntax comparison than anything automated, but nickf makes a good point in that the real cost need not be too great. We only used Prototype on a few pages that really needed a high level of interactivity, so as long as mind out Ps and Qs it should not hurt to use jQuery everywhere else.

Categories

Resources