Tips and tricks #12: Long (infinite) calculations
This article describes how to perform long or infinite calculations while allowing user to stop them
Tips and tricks series
- Tips and tricks #1: How to set output value
- Tips and tricks #2: How to make calculator translatable into different languages
- Tips and tricks #3: How to make calculator with custom errors
- Tips and tricks #4: How to make calculator with table output
- Tips and tricks #5: How to show/hide input and output controls in a calculator
- Tips and tricks #6: How to make calculator with virtual keyboard
- Tips and tricks #7: How to make calculator with SVG image map
- Tips and tricks #8: How to reuse existing calculator
- Tips and tricks #9: Big numbers
- Tips and tricks #10: Files, long calculation mode
- Tips and tricks #11: Dynamic table columns
- Tips and tricks #12: Long (infinite) calculations
- Tips and tricks #13: Bitmaps and Pixel manipulation
- Tips and tricks #14: How to use a masked input
This article may rely on knowledge you should get from previous articles, so you may want to check them first.
To use this feature you have to check the calculator option "Long (infinite) calculation". With this option, your calculation will be performed on a separate thread by the web worker as series of calculations, allowing user to stop them if he wishes.
Technically, with this mode, you are given the progressControl object, which should be used to organize series of calculations, with the help of context property, which is carried from calculation to calculation and stop and repeat methods to stop series or schedule next calculation respectively. Below you can find a code snippet that demonstrates this technique.
if (n === 0) return PCR.integer(1);
if (!progressControl.context) {
//set the default values for output parameters
factorial.SetValue('1! = 1');
//initialize the context
progressControl.context = {
current: PCR.integer(1),
m: 1
};
//schedule next iteration
progressControl.repeat();
} else {
//get the context
var data = progressControl.context;
//perform the calculations
data.current = data.current.mul(++data.m);
//update the output parameters
factorial.SetValue(data.m + '! = ' + data.current.toString());
//stop the iterations or schedule next iteration
if (data.m != n)
progressControl.repeat();
else
progressControl.stop();
}
That's it. And you can check the result below, just enter something around 1000 at least
Comentarios