Red Whale Red Whale - 6 months ago 10
Javascript Question

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

<script>
var fn = function(url){
// bla bla bla...
};
</script>

<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
fn()
function will be executed.

Suppose the
fn()
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

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

Comments