1

I was looking for any solution for my problem:

I want a program, using JavaScript, that executes a mathematical operation for X amount of time. Is it possible? Is there a way to interrupt the current execution thread using JavaScript or some other libraries?

What I want is, have a mathematical operation executing itself into a loop and, for example, in a minute finishes even if the loop isn't complete.

(The only way I think something similar is asking during the loop if the amount of time is minor than 1 minute, but I don't want to do busy waiting)

The mathematical operation is:

var serie = 0;    
for ( var j=1; j <= 5; j++ ){
    for ( var k=1; k <= 100000; k++ ){
        serie = serie + ( Math.log(k)/Math.LN2 ) + (3*k/2*j) + Math.sqrt(k) + Math.pow(k, j-1);
    }
}
Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
Juan Fernandez Sosa
  • 570
  • 1
  • 5
  • 19
  • 2
    [Web Worker](https://developer.mozilla.org/en-US/docs/Web/API/Worker), [Using Web Workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers) – Andreas Jun 29 '16 at 13:36
  • @JuanFernandezSosa I am almost sure that there's a mathematical formula you can apply here so that you don't need to brute force it like this. Look into the math side of things, you'll might find something that allows you to complete this without the massive loop. – Madara's Ghost Jun 29 '16 at 13:39
  • Also, what computer are you running this on? This is taking me 20ms to run, a minute is pretty extreme for 500k operations. – Madara's Ghost Jun 29 '16 at 13:41
  • 1
    @MadaraUchiha I must change the code so it can take more time to execute. It was just an example – Juan Fernandez Sosa Jun 29 '16 at 13:43
  • That's fair. This does sound like a classic problem for Web Workers, so look at the links provided by Andreas a few comments above mine. It should give you an idea of how to solve it (it essentially opens a different thread and executes there, then returns the result to you, you can terminate it from the main script at any time) – Madara's Ghost Jun 29 '16 at 13:46
  • Yes, i think the solution proposed by @Andreas could work. i mean, i've made some tests and it seems fine. – Juan Fernandez Sosa Jun 29 '16 at 14:02

1 Answers1

-2

You can use the clearInterval() and setInterval() methods to time your functions.

asehgal17
  • 31
  • 1
  • 6