Search code examples
iosiphoneios7uiwebviewios8

iOS UIWebView Javascript Timers


If a page loaded into a UIWebView contains a Javascript setInterval() call, what is the behavior of that timer when the phone goes sleep?

Is there any point in time when all timers are stopped?

Will the timers be restarted when the phone is woken up? If so, does the timer start at where it was paused, or started from 0?


Solution

  • WebKit internal timer management is a little peculiar in general, and in particular in iOS. They are registered in NSDefaultRunLoopMode mode, so for example, when scrolling in UI, Javascript events do not fire, but they are not aggregated either, like with regular timers (NSTimer).

    To answer your question, when the application process is suspended, the timers are also suspended, so they will not fire while the process remains suspended. Once the process is resumed for whatever reason (user opened the app, background fetch, etc.), the timers will resume their run, and will resume to the relative point of when the last tick was supposed to be.

    So if you set a timer for every 10 seconds, and close the app at t+1 seconds, then open it again at t+35 seconds, the timer will fire after 5 seconds; you would not hear retroactively the t+10, t+20 and t+30 seconds ticks.

    Note: This is the in-process model based timer management of UIWebView /WebKitLegacy/; I am not quite experienced with how WKWebView /WebKit2/ handles them.