0

I've got

function doSome(){}

What should I do if I want stop execution of this function when it's executing more then 200 mills?

Thanks a lot.

3 Answers3

1

I guess 200 milliseconds it's a little to short, but:

  • if you have a while loop, create a Date object before entering the loop and a new one in the loop. If the difference is greater than 200, break it

    start = new Date()
    while (1) {
        end = new Date()
        if (end - start > 200) break
        // work
    {
    
  • If you're executing Ajax call, see aborting AJAX call

Community
  • 1
  • 1
ep0
  • 710
  • 5
  • 13
0

A web worker can be terminated with its terminate function. There is no other way to interrupt execution of Javascript from within Javascript itself. Note that many browsers also have slow script detection which prompts the user when a script runs a certain amount of time or number of instructions. This is not controllable from Javascript, however.

Dark Falcon
  • 43,592
  • 5
  • 83
  • 98
0

Depending on the kind of algorithm that is implemented within the function, you could check how long it's been running, but it isin't very precise and you would have to make sure that each loop iteration takes very little time to process.

For instance:

function doSomething() {
    var startTime = new Date.now(),
        i = -1,
        itemsToProcess = [1, 2, 3, 4],
        len = itemsToProcess.length;

    while ((Date.now() - startTime) <= 200 && ++i < len) {
        //process items here
    }
}

You could also avoid the freezing by giving the browser some time to breath using setTimeout or setInterval. That is probably a better approach if you want to task to always complete.

function startDoSomething(items, delay) {
    var i = arguments[2] || 0;

    //process
    console.log('processing item at: ' + i);

    if (++i < items.length) {
        setTimeout(function () {
            startDoSomething(items, delay, i);
        }, delay);
    }
}

Finally, a much more efficient way to handle long-running processes would be to use a web worker, you can't directly update the DOM from the worker.

plalx
  • 42,889
  • 6
  • 74
  • 90