Red Whale Red Whale - 2 years ago 71
Javascript Question

Is there any way to forcibly abort a JavaScript (or jQuery) function which is being executed?

var fn = function(url){
// bla bla bla...

<input type="button" onclick="fn()" value="Execute">
<input type="button" onclick="???" value="Abort">

Just like above, when a user click on the “Execute” button, the
function will be executed.

Suppose the
function will run for a very very long time, and if the user want to stop the execution of this function midway, how should I do?

Answer Source

Functions in JavaScript are blocking -- which means that everything[1] freezes as the function runs. The screen doesn't redraw, mouse clicks are not processed, keyboard events are not processed.

Nothing happens until the function is done.

The only way to counter this is to use async coding to run your code in small, bite-sized chunks.

There are a number of tools to use, including:

I'd recommend looking at the async tools then asking another question on how to make your function non-blocking.

[1] For the purposes of this discussion

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download