Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How does this code work? #32

Open
NicolasWinsten opened this issue Mar 31, 2023 · 3 comments
Open

How does this code work? #32

NicolasWinsten opened this issue Mar 31, 2023 · 3 comments

Comments

@NicolasWinsten
Copy link

Hello,

many thanks for this hack. But I would like to know how it actually works?
How does the webworker keep javascript timers going?

thank you for any help

@ivanff
Copy link

ivanff commented Apr 28, 2023

yes, it still works, thanks to Ruslan

@saurav-codes
Copy link

i also want to understand how does it works? do we simply link the script before timer script.?

@turuslan
Copy link
Owner

Hello.
Sorry for late comment.

Scripts may create frequent timers

window.setInterval(action, 10ms)

Frequent timers consume more battery
(also these timers can be used for annoying things like ads)
so browsers throttle window timers (reduce frequency, increase delay)
when tab or windows becomes background.

action() after 10ms
action() after 10ms
action() after 10ms
// tab becomes background
action() after 1000ms
action() after 1000ms
...

Although window.setInterval is slowed down,
but there seems to be several techniques that work around that.

One of them is using Worker.
Worker is created on separate thread from window's ui thread.
Seems that browsers don't throttle Worker timers.
Worker can postMessage to window,
which calls window.onmessage.
Seems that browsers don't throttle window.onmessage too.

This library overwrites window.setInterval function
and forwards setInterval call to Worker via worker.postMessage,
remembering original window callback.
Worker calls self.setInterval and worker callback
calls self.postMessage to wake window.onmessage,
which calls original window callback.

flowchart TB
    subgraph window
        a1("window.setInterval(action)")
        a2("worker.postMessage()")
        a6("worker.onmessage")
        a7("action")
    end
    subgraph worker
        a3("self.onmessage")
        a4("self.setInterval()")
        a5("self.postMessage()")
    end
    a1-->a2-->a3-->a4-->a5-->a6-->a7
    a1-. "action()" .->a6
Loading

Library script hacktimer.js overwrites window.setInterval.
It must execute before any other script.
If some other script will execute before,
it will call slow window.setInterval version.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants