AngularJS Focus Only Timeouts
Today’s blog is about a little factory I created to solve a particularly interesting problem, basically we have a timer on our page that updates every second and I didn’t want or need that timer to update whilst not on the page so I developed a widget that does the following:
– Only runs the timeout when the page is focussed.
– Allows the pausing and un-pausing of all timeouts registered with it.
– Allows pausing of individual timeouts by name.
– Allows removing timeouts from the page.
The JSFiddle has some issues due to it being in frames or something like that, but does work if you run it in a new tab/window (you should be able to right click and select “Open in new…”).
For using the factory, the functions you will need to use are:
FocusOnlyTimeouts.addTimeout(unique_name_string, function, timeout_in_milliseconds); //runs the function passed as if used in a recursive timeout function. - note that the function must be a reference or a function itself, ie example not example() otherwise the function will only be run when the timeout is added to the factory. FocusOnlyTimeouts.pauseTimeout(unique_name_string);//pauses the named timeout FocusOnlyTimeouts.unpauseTimeout(unique_name_string);//unpauses or restarts the named timeout FocusOnlyTimeouts.pauseAll();//pauses ALL timeouts FocusOnlyTimeouts.unpauseAll();//unpauses or restarts ALL timeouts FocusOnlyTimeouts.stopTimeout(unique_name_string);//the timeout function will not be run again and the timeout will be deleted from the factories memory