Pausing JavaScript execution for animation of code - javascript

I'm having an interesting but difficult problem with my JavaScript code. Basically, I'm trying to create an animation of a simple algorithm using JavaScript (a sorting algorithm, if you're wondering) for educational reasons. I've already got all of the animation code written (using RaphaelJS), and it all works fine. The trouble is getting the animations of the algorithm to happen at the right time. JavaScript doesn't really have any way to "pause" execution, so I can't really step through the algorithm slowly, playing animations at each step. It's obviously much more valuable from an educational perspective if the algorithm proceeds at a pace the student can comprehend.
There are two ways to solve this problem that I can think of, and both suck. The first is to use some crazy setTimeout() code. This would probably be very difficult -- lots of strange code transformations would be needed to associate the different parts of the algorithm with correct timeouts. I've already tried to do this a little bit, and it gets very complicated for a non-trivial algorithm.
The second is to busy-wait. This would probably also work. The problem is that busy waiting is a pretty bad idea in JavaScript code -- I actually crashed Firefox when I was testing out this alternative. Basically, I'm wondering if there's another solution here that I'm overlooking. Bonus points if the solution is client-side only, since the amount of freedom I have to serve stuff other than static html and javascript on the school server is questionable.

It's obviously much more valuable from an educational perspective if the algorithm proceeds at a pace the student can comprehend.
What about using links/buttons e.g. < > to allow the user to step through the code by clicking prev/next?
Maybe the only viable workaround and may make more sense for the end user.

Maybe this is too simple to do what you want it to do, but what if you put the segment of code that you want to run between stops into a function, and call that function with the push/click of a button on the page: onclick="runAnimationPiece()"
Your code would need to hold some state to know where it left off from the last time the function ran.
And if you need to run different functions for different pieces of the animation, say, for instance, the first piece should be generated by foo1() and second piece by foo2(), you can create a counter and a function which calls the appropriate animation function (foo1() or foo2(), etc.) based on the counter.

Related

Javascript: What's the difference between assigning a value globally or inside an 'initialising' function?

I watch a lot of programming tutorials and challenges using HTML5 canvas and Javascript (mainly by Dan Shiffman or The Coding Train) and I try to follow along while changing the code in order to make it my own.
I've noticed a lot of the programmers creating variables (e.g. let num;) and then assigning the values inside of an init() function.
What is the difference between doing that and just assigning the value to the variable in the same line (e.g. let num = 1;)?
I've tried doing both and I don't see a difference so I'm thinking it's maybe a slight performance boost?
Assigning the values inside a function will allow you to call that function from anywhere, rather than being stuck at assigning only at the initialization location. From a practical perspective, assuming you understand scope and the temporal dead zone, this can be helpful for:
Code organization. If you put the meat of your code into functions and then call the functions all together later, it can be easier to visualize the higher-order process of what's going on, and in what order the various chunks of code need to run in. If the code is long, it can be easier to understand what init() means than to understand what <200 lines of setup code> means.
Less repetitiveness. Say that at some point when the application is used, either you or the user want to reset the state of the app back to how it was originally. (For example, a "Play Again" button on a game.) Then, rather than having to write <200 lines of setup code> again, you'd just have to write init() again.
maybe a slight performance boost?
This has no effect on performance.

Processing.js sleep

I want to write a sleep() function in javascript/processing.js. I.e: a function that interrupts the flow of the program for however many seconds.
It is obvious how to do this with "busy waiting", but this tends to slow down the browser and make things unusable
I know "sleep" is not good javascript. I want this function for didactic purposes (help kids understand their code), not for production use.
Since it is meant do be didactic, an explicit callback is too much of a complication. Calling the function should be as simple as in , say, bash or php -- however, we can use the most arcane things, just as long as they remain hidden inside the sleep function (including processing.js tricks)
I am aware of question What is the JavaScript version of sleep()?, but still hope there is a hack to stop processing.js (or perhaps a real javascript solution, however ill-advised it might be)
This function should work outside a draw() loop -- if it works inside as well, that is a bonus
If it is relevant, this function is meant to be used on Khan Academy
It is obvious how to do this with "busy waiting", but this tends to slow down the browser and make things unusable
A sleep() function would also cause this behavior, since JavaScript is single-threaded.
Since it is meant do be didactic, an explicit callback is too much of a complication.
You've pretty much answered your own question: there is no way to do a sleep() function in JavaScript without using a callback or busy waiting.
You might consider using Java mode to show sleep(), but it sounds like busy waiting is the way to go.
And in my humble opinion, even if you could find a hack to cause a sleep, that's probably not a great example for kids, since their code would never do that. They're much more likely to try to render too many objects. If you're trying to demonstrate that doing too much inside of the draw() function will be bad, then why not just have them do too much inside the draw() function? Teach them about for loops and then ask them to see what happens when they draw 100 rectangles, or 1000, or 1,000,000!

is Javascript's setInterval loop a resource hog?

I'm designing an app to run on very low spec machine..and i needed it to be efficient as possible..
I needed to issue around 10 intervals at every second that simply makes an ajax call.. and then does a few add/remove classes and (think of it as SERVER Status monitor)
I know in FLASH (oh good old flash days) having a lot of intervals can cause processor spikes .. so i'm very conservative with issuing setIntervals in AS 2.0 before.
I was wondering if this is the same case with JS? or is it alright for JS to have a bunch of intervals (that does lightweight tasks) running? I noticed a lot of sites do this , even facebook has tons of intervals running, loading scripts, etc..
And oh, for one interval, I wanted to run it at 50ms (it loads as status.php link) ... this ok?
I could probably optimize my interval calls, no problem but i'm just wondering how "heavy" or "lightweight" background intervals are in JS..
Thanks all
10 intervals at every second meaning a call every 100ms should not be an issue in my opinion, but if you ask me I would fire a call every 250ms.There is not much difference between the two that the user will notice.
Also make sure that there is a mechanism to handle long running response from server in case there is a delay and stop the interval firing if there is drag.
As a matter of personal feeling, I tend to prefer setTimeout over setInterval -- to the point I don't use setInterval at all.
The issue that you might run into is if one process takes longer than it should -- let me give you an imaginary situation:
window.setInterval(takes100msToRun, 50);
window.setInterval(takes50msToRun, 50);
window.setInterval(takes20msToRun, 50);
The problem is that the first interval will take longer than it should, so the second two interval requests are now behind and the browser will try to catch up by running them as quickly as then can. The second interval takes 50ms, -- so its still running behind when the third interval hits.
This creates an ugly situation that can lead to a lot of drag.
On the other hand, if you setTimeout, then you aren't say "Run this every 50 ms", but rather "Run another one of these 50ms from we finish." (Assuming, of course, that the functions set up another setTimeout to re-execute.)
It is absolute rubbish for things that need good clock timing, but its superior for everything else.
setTimeout and setInterval will affect performance, but little.
Since there are lots of functions triggered/listening/running in the browser.
Even a tiny operation like move your mouse to vote up for this answer, there are thousands of events got triggered, and tens of functions start running.
Don't use setInterval. As a matter of fact, the library underscore doesn't use it either.
See how they implement the _.throttle without setInterval.
http://learningcn.com/underscore/docs/underscore.html#section-66

Is there is any way to call a function when an infinite loop or browsser hangs in javascript?

hi i m working a project which have huge javascript code sometimes javascript code executes automaticaly and hangs browser with message "kill this page" in chrome is there is any way to track the error .like calling calling a function when infinite loop arrives or browsser hangs like that .please give me some suggestion about debugging javascript code plz.
There is no way of doing what you wish inside javascript.
However you can use a tool like DynaTrace Ajax Edition to trace cpu usage in the browser to identify what is happening.
Infinite loop can be caused in many different bad programming logic, and there is no reliable logic to detect in every case. So I highly doubt if any programming language or IDE would offer any reliable infinite loop detection.
What you saw was basically a runtime detection based on how long script execution has taken before the browser could update and refresh the UI.
Sometimes this kind of long running JavaScript could be caused by infinite loop, but many times they are just big loops or loops that perform too much work that makes UI unresponsive.
Because JavaScript is not multi-thread, therefore to avoid the later case above, you could consider breaking the loops into small units of work, once a unit is finished, don't run the next unit, but instead call the next unit of work with setTimeout with a small time delay (such as 250ms). This would give the browser a chance to breath and update UI, and unmark your script as "long-running" script.
You may also use logging such as Firebug Logging to log the loops with enough values that help you find out if those loops are indeed infinite loops.

repeat $() all over the place or declare once and reuse?

Using jQuery, if I am writing code like this
$('blah').doSomething();
//bunch of code
$('blah').doSomethingElse();
//bunch of code
$('blah').doOtherStuff();
Is a new jQuery object being created each time I say $('blah') ?
If so, would it reduce object creation overhead to do something like this instead:
var blah = $('blah');
blah.doSomething();
//bunch of code
blah.doSomethingElse();
//bunch of code
blah.doOtherStuff();
Make sense?
Absolutely correct!
Why Cache
Another benefit of caching is code maintainability. If the selector is only in one place, changing it only needs to be done in one place. Trust me that makes life easier when maintaining code.
Chain
Although you can go one step further (where relevant), and chain your calls:
$('blah')
.doSomething()
.doSomethingElse()
.doOtherStuff();
This is slightly better for 2 reasons. Firstly, you're not using the extra variable, so you save a tiny amount of memory. Secondly, the language doesn't perform lookups for each identifier use, so it's quicker.
So, why do people still [over]use $()
One reason people use lots of $() is because they don't know any better.
Another reason is because element selection used to be slower. But as with most things in the browser, querying objects with selectors is fast being optimised (document.querySelectorAll), which means it's not such a big deal to cache or not to cache, so maybe with that in mind they allow themselves not to cache.
Finally, there are benchmarks hanging around (one two from a quick google) that try to claim that it doesn't matter or is maybe even faster not to cache. The problem with most of these benchmarks and why I suggest you be very wary about drawing conclusions from them, is that the DOM in the example is not real-world; it's overly simplistic. Secondly, the selectors are simplistic as well. So of course querying will be lightning fast and caching won't make a big difference, but I don't find them at all conclusive.
That said, if your example is similar to those of the benchmarks, then maybe you can draw your own circumstantial conclusions, and caching might just be a nuisance.

Categories

Resources