Javascript error - Blocking IE performance - javascript

I am trying to run a script, which is intense(that is lot of loops etc.). When I am trying to call this method in loop, I am getting an error:
"The JavaScript operation is blocking the normal operation of IE. Do you want to stop running the script?" Yes No.
Is there something I am missing? I have seen worse scripts running just fine.

If your script does that, you might want to re-engineer your code.
If your code really need to loop for that long you will be dealing with some timeouts in your script to stop every time you think is necessary to avoid this "behavior"...
I recommend to check this post JavaScript and Threads

Related

Is it possible to implement a sleep() in javascript?

This is a duplicate question. It has been asked many times before, with dozens of answers, some of them rated very highly. Unfortunately, as far as I have been able to tell, every single one of those answers is a variant of "You don't, it's bad programming practice. Use setTimeout instead".
This is Not. An. Answer!
There are some use cases - rare but they exist - where you might want the entire page's execution to halt for a second or two, and I find it very frustrating that nobody seems interested in answering the actual question. (have a look at the comments here for some examples).
I am sure it's possible to halt javascript executing; for instance, if I use firebug to insert a breakpoint, then the execution stops when it hits that point. So, firebug can do it. Is there some way that the program can halt execution of the current thread until some timeout occurs?
Just some thoughts: How does firebug do it? Is there some browser-specific method? Is it possible to trigger a stop, without specifying a timeout to continue? Could I programmatically insert a breakpoint, or remove one? Could I get a closure representing the current thread to pass to setTimeout?
I don't have a specific use case in mind; I am just looking for advise from someone who knows the browser/javascript design better than me, as to how this can most effectively be done.
So far, I have come up with only one solution:
endtime=Date.now()+1000;
while(Date.now() < endtime)
$.ajax(window.location.origin,{'async':false});
This appears to work. The problem with it is, it makes hundreds of excess requests. I would replace the location.origin with something like mysite/sleep?delay=X and write a server side script to provide the delay, which would but it down to one, but the whole thing still seems really hacky. There must be a better way to do this! How does the jquery.ajax function manage it? Or is there a busy-wait buried in it somewhere?
The following do not answer the question and will be downvoted, just because I am sick of seeing pages of answers that completely ignore the question in their rush to rant on the evils of sleep:
Sleep is evil, and you should do anything it takes to avoid needing it.
Refactor your code so that you can use setTimeout to delay execution.
Busy-wait (because it doesn't stop execution for the duration of the sleep).
Refactor your code to use deferred/promise semantics.
You should never do this, it's a bad idea...
... because the browser has been, traditionally, single-threaded. Sleeping freezes the UI as well as the script.
However, now that we have web workers and the like, that's not the case. You probably don't need a sleep, but having a worker busy-wait won't freeze the UI. Depending on just how much you want to freeze a particular thread, I've seen people use:
endtime = Date.now()+1000;
while (Date.now() < endtime)
or, curiously (this was in an older but corporate-sponsored analytics library):
endtime = new Date().getTime() + 1000;
while (new Date().getTime() < endtime)
which is probably slower. If you're running a busy wait, that doesn't necessarily matter, and allocating objects probably just burns memory and GC time.
Code using promises or timeouts tends to be more modular, but harder to read (especially when you first learn async techniques). That's not an excuse for not using it, as there are definite advantages, but maybe you need everything to stay synchronous for some reason.
If you have a debugger running and want some chunk of code to pause itself (very useful when you have a bunch of nested callbacks), you can use:
function foo() {
do.someStuff();
debugger;
do.otherStuff();
}
The browser should pause execution at the debugger statement. The debugger can almost always pause execution, because it is in control of the VM running the code; it can just tell the VM to stop running, and that ought to happen. You can't get quite to that level from a script, but if you take source as text (perhaps from a require.js plugin), you can modify it on the fly to include debugger statements, thus "programmatically inserting breakpoints." Bear in mind that they will only take effect when the debugger is already open, though.
To capture the state of a "thread" and persist it for later use, you may want to look into some of the more complicated functional programming concepts, particularly monads. These allow you to wrap a start value in a chain of functions, which modify it as they go, but always in the same way. You could either keep simple state (in some object), or record and reproduce everything the "thread" may have done by wrapping functions in functions. There will be performance implications, but you can pick up the last function later and call it, and you should be able to reproduce everything the thread may have done.
Those are all fairly complicated and specific-use solutions to avoid just deferring things idiomatically, but if you hypothetically need them, they could be useful.
No, it is not possible to implement a sleep in javascript in the traditional sense, as it is a single-threaded event based model. The act of sleeping this thread will lock up the browser it is running in and the user is presented with a message either telling them the browser has stopped responding (IE) or allowing them to abort the currently running code (Firefox).

Methods to reduce apparent lag to client from large javascript operations

As part of my Chrome Extension, I am performing a few regex replaces on a lot of (upwards of 3000) elements on the document end event. In the worst cases, in Chrome 34.0.1847.116 m on a pretty decent PC, the operation can take >180 seconds to complete, and during this time, the webpage is frozen.
Is there, and if so, what is the best way to either mitigate the operation over a longer time span, or give the operation a "lower priority" so that it doesn't take 100% while running.
The script is pretty much nested jQuery each functions all running a regex replace using a large expression. These expressiond search for 3000-4000 words and then replaces it with some html. An example one is (searching for specific reddit names)
/(\s|/u/|^)(name1|name2|name3|...|name500)([^\w]|$)/
If it helps, you can see the full source here.
Thank you for your time.
You can run the long operations in a new thread using the setTimeout function and a callback on completion.
See Javascript Create New "Thread"

How to fix firefox stop javascript when not responding

I'm currently create a javascript that run a loop forever. However, after a few hours my script stop working, it asks me to continue or stop script. Is there anyway to fix this or use some automation tools to restart firefox and run the javascript again. Because most of time I away from keyboard
id strongly recommend not using any kind of infinite loop - doing so would be just asking for trouble. instead you want to look into using javascript's setTimeout() and/or setInterval() functions... allowing you to specify a block of code to run every X milliseconds
you can find the docs here
setTimeout()
setInterval()
To prevent the long running javascript prompt, you need to occasionally let javascript process other events. The classic way to do this is like this is using setTimeout().
function doNextChunkOfWork() {
// do some work here
if (moreWorkToDo) {
setTimeout(doNextChunkofWork, 1);
}
}
Using the setTimeout() lets the javascript engine get back to its event queue and process other events and thus prevents the long running script warning.
If you explained what you're really trying to do, we might be able to suggest even better options. If you're doing some sort of infinite loop, javascript in a browser is meant to be an event-driven environment where the usual mechanism is to create event handlers and let events trigger code to run. It is not meant for infinite loops polling for something.

Asynchronous programming in javascript (NOT AJAX)

Is it possibly to do things asynchronously in javascript (AJAX aside)? For example, to iterate multiple arrays at the same time. How is it done? A brief example would be nice. Searching for this was hard, due to all the ajax pollution, which is not what I am looking for.
Thanks in advance.
Use web Workers. But remember that it is a very new feature and not all browsers are fully supported.
You could use setTimeout.
setTimeout(function () { iterateArray(array1); reportDone(1); }, 0);
setTimeout(function () { iterateArray(array2); reportDone(2); }, 0);
I'm not sure how concurrent it will be, but it is an asynchronous programming model.
As stated by Grumdrig you can write code like this:
setTimeout(function () { iterateArray(array1); reportDone(1); }, 0);
setTimeout(function () { iterateArray(array2); reportDone(2); }, 0);
But it will still not run concurrently. Here's a general idea of what happens after such timeouts are called:
Any code after the setTimeout calls will be run immediately, including returns to calling functions.
If there are other timers in queue that are at or past their delay or interval time, they will be executed one at a time.
While any timer is running, another might hit its interval/delay time, but it will not be run until the last one is finished.
Some browsers give priority to events fired from user interaction such as onclick and onmousemove, in which case the functions attached to those events will execute at the expense of timer accuracy.
This will continue until there is an opening (no previously called timers or event handlers requesting execution). Only then will the functions in the example code be run. Again one at a time, with the first one likely but not certainly executing first. Also, I'm venturing a guess that some browsers might impose a minimum delay time, which would make any timers set with a delay of 0 milliseconds be run even later than expected.
Obviously there is no performance advantage to running code like this. In every case it will make things take longer to complete. However in cases where a single task is taking so long it freezes the browser (and possibly trips "Script is taking too long" browser warnings), it can be helpful to break it up into smaller faster executing pieces that run sequentially after some delay time, thus giving the browser some time to breathe.
Web Workers have been mentioned, and if you are not concerned about IE compatibility then you can use them for true concurrency. However there are some severe limitations on their use imposed for security reasons. For one they cannot interact with the DOM in any way, meaning any changes to the page still must be done synchronously. Also all data passed to and from workers is serialized in transit, meaning true Javascript objects cannot be used. That being said, for intensive data processing, Web Workers are probably a better solution than breaking a function up into multiple timer delayed tasks.
One new development in this field is HTML5 Web Workers.
JavaScript is normally single threaded; you cannot do several things at once. If your JavaScript code is too slow, you will need to offload the work. The new way is to use web workers, as others have noted. The old way is often to use AJAX and do the work on the server instead. (Either with web workers or with AJAX, the arrays would have to be serialized and the result deserialized)
I have to agree with MooGoo, i also wonder why you would run through such a big array in one go.
There's an extension to JavaScript called StratifiedJS, it allows you do multiple things at once as long as they're asynchronous. Also, webworkers are an awkward "solution" that just make things more complicated, also, they don't work in IE.
In StratifiedJS you could just write.
waitfor {
// do something long lasting here...
}
and {
// do something else at the same time...
}
// and when you get here, both are done

Disabling script max-execution-time in flex?

How do I completely disable the max-execution-time for scripts in flex? The configurable max is 60 seconds, but I'm calling off to other interactive processes which will probably run much longer than that. Is there an easy way to disable the maximum script execution time across my entire application?
you can't. and probably, that's quite good. of course it's a pitty that you can't but when looking at the kind of things some people fabricate with the flash player, I am very happy.
For simplicity Adobe decided to promote a single threaded execution model that allows concurrent operations through asynchronous callbacks. sometimes this becomes anoying, verbous and even slower (performing a big calculation in a green thread simply takes longer than doing it directly). It's more of a political choice, so I guess the best you can do is live with it.
or you could explain what exactly you're up to, so I could propose a solution.
p.s.: there has been quite a lot of discussion going on about threads for background calculation. also, some people use seperate SWFs to perform calculation, or push it to pixel bender. also, you may wanna have a look at alchemy. it supports threading through relatively efficient continuation passing.
I have a long-running SOAP request that times-out with Error 1502. "Error #1502: A script has executed for longer than the default timeout period of 15 seconds."
I went to the right-click Properties dialog on the project in Flash Builder 4, then the Flex Compiler Options.
I set the Flex Compiler Options to "-locale en_US -default-script-limits 1000 60".
The locale was already there. It was the -default-script-limits that was cryptic to decipher from the compiler reference.
But I still got the fault with Error 1502 and 15 seconds. I even did a Project->Clean... command and tried again.
So, where is that 15 second timeout set? It turns out -- from some Googling and I'm not entirely sure -- that the Flex compiler accepts my setting, but the timeout message is fixed text with the 15 seconds message.
I also found that I could try: -default-script-limits 1000 65535. That didn't help either. This is from a posting on FlashDevelop.org 1
The bottom line for me is that I now need to page or otherwise divide up the information I am requesting in the SOAP call. My code still works fine for small requests.

Categories