I am new to JavaScript so probably my question might look somehow primitive.
So I have an HTML file a.html
and I have a JS file b.js
with some API functions inside and a loop (explained shortly).
There is a common array q
, defined as a window
field inside of HTML (so it is accessible through window.q
).
The API functions defined inside of b.js
are used throughout a.html
(for actions inside button tags, also inside script tags etc.), for example:
<script src="b.js" async></script>
<button onClick="onClick1()">1</button>
<button onClick="onClick2()">2</button>
<button onClick="onClick3()">3</button>
<button onClick="onClick4()">4</button>
<script>
function onClick1() {
api_f1(...);
};
function onClick2() {
api_f2(...);
};
function onClick3() {
api_f3(...);
};
function onClick4() {
api_f4(...);
};
</script>
What those API functions actually do, they push objects into that common array q
, and b.js
has a function called execute()
which pulls out a first element of q
(using q.shift()
):
var execute = function() {
var nextEvent = window.q.shift();
//do something with nextEvent here
};
Now my question is,
How should I implement the loop inside b.js
that will continuously call function execute()
and retrieve the element from q
or wait until there is an element if q
is empty, without hogging the CPU?
I tried this:
while(1)
{
while(window.q.length==0)
{}
execute();
}
but the page hangs,
Then I tried this:
while(1)
{
while(window.q.length==0)
sleep();
execute();
}
This one was able to retrieve objects if I called API functions directly from <script></script>
tags, but if I place them into button actions, the loop simply stops, while it was supposed to wait inside while(window.crl8.q.length==0)
loop.
UPD. The loop in the second snippet stopped because there's no sleep()
function defined. I replaced it with await sleep(1000);
but the loop stops again without reaching execute()
(no error this time)
Any ideas how I could implement this loop efficiently?