I want to patch alert
object in browser, to show additional text, but i need to await some data to show necessary content in alert. However, i can't postpone alert
call.
Also, i don't know about way to close alert and show other alert without user action (if it exist, it can solve my problem too).
So, i have to await some data, but i can't break alert
behavior, which is block execution of the code.
To await response, i can do something like this
var start = performance.now();
while(true) {
var time = performance.now() - start;
if (time >= 3000) break;
}
console.log('done');
But instead check timer i will check some data.
This way should work, but this is terrible for performance, because opposite to alert
which is just freeze thread and do nothing until close dialog we'll load CPU with useless work.
Is possible freeze a thread more energy efficient?
I have to freeze thread until get some data from worker.
Why promise is not solve your problem?
Promises is not block a main thread, so this is not reproduce behavior of alert
which i need.
The blocking thread is not user friendly and it's not that you need to await some data
I know about it, and this note is fair enough to development web pages and applications.
But this case is special, i develop feature for a browser extension, to translate alerts. Browser extension must not modify behavior of the page. So when web site is call alert, thread must be freeze. Browser extension must not postpone a alert
call to avoid unexpected behavior on the page.
You can see feature explaining here: https://github.com/translate-tools/linguist/issues/102
CodePudding user response:
The only way I can think of to "block" without consuming CPU this would be to make a synchronous XMLHttpRequest (which are deprecated because blocking is not user-friendly). You'll need to set up a server that can read the payload of the request and reply after the specified amount of time.
const xh = new XMLHttpRequest();
xh.open('GET', urlToYourServer, false);
xh.send('3');
where that '3' is the request body that the server parses (and responds after 3 seconds).
That said, you should not do this - it's a very inelegant and user-unfriendly approach. It'll stop any other action (including browser repainting and other requests) from occurring while this is going on. Better to properly wait for whatever you need (whether that's through a .then
of a Promise, or a callback, or something else) - but without more context in the question, how exactly to accomplish this is unclear.