<p>When writing a game's event loop, I always rely on a function from an external library, like <code>draw()</code> in <code>ProcessingJS</code> for JavaScript, or <code>.after()</code> from <code>tkinter</code> for Python (or <code>DispatchQueue.main.asyncAfter()</code> from <code>GCD</code> for Swift).</p>
<p>Something like this:</p>
<pre><code>import tkinter as tk
window = tk.Tk()

def eventLoop()
    # Do Stuff Here
    
    window.after(1000//framesPerSecond, eventLoop)

eventLoop()
window.mainloop()
</code></pre>
<p>It's <em>called</em> an event loop, but it's actually a function, not a loop. If you tried to implement one as an actual loop, like my very first attempt when I had just started learning programming, it wouldn't work because it would &quot;block&quot; the main thread and not allow any user interaction:</p>
<pre><code>// Faulty Event Loop

while(true) {
    // Do Stuff Here
}
</code></pre>
<p>This is the difference between <em>synchronous</em> (the <code>while</code> loop) and <em>asynchronous</em> (all the library functions) execution.  I'm aware that a programming language doesn't have to be multithreaded to allow asynchronous execution, and that there are native ways of designating a function asynchronous (like <code>async</code>/<code>await</code> in JS), but haven't been able to find any equivalent for a loop construction.</p>
<p>The closest I found was this question on StackOverflow: <a href="https://stackoverflow.com/questions/39110762/while-loops-using-await-async">https://stackoverflow.com/questions/39110762/while-loops-using-await-async</a> but the answers to the question suggest wrapping the loop <em>inside</em> an asynchronous function because the loop itself at the global level wouldn't be asynchronous.</p>
<p>But why not?  Why isn't there some syntax such as</p>
<pre><code>// Hypothetical native JS asynchronous loop

async while(true, 5) {
    // Do Stuff Here every 5 seconds
}
</code></pre>
<p>that could be used from the global scope to specify an infinite loop with 'spaced-out' iterations that don't block the main thread?  Theoretically, it could work by the same mechanism as <code>async</code>/<code>await</code> but using a loop instead of a function.</p>
<p>Would this be problematic to implement, or are there programming languages I'm not aware of that actually <em>do</em> implement something like this?</p>

<implementation><loops><async>
Built-In Asynchronous Loops (Not Functions) - Do they / could they exist?
CC BY-SA 4.0
2023-07-05T20:10:18.103Z
Apple's `Timer` object provides basically this, doesn't it?
Bbrk24
CC BY-SA 4.0
2023-07-05T20:11:11.810Z
This is basically just JS's `setInterval` right? It could also just be implemented in any language with `async` by `await`ing a delay at the end of each loop iteration (in fact, most languages that _do_ have `async` probably provide non-blocking `async` versions of `sleep`)
rydwolf
CC BY-SA 4.0
2023-07-05T20:13:24.110Z
@RydwolfPrograms I have written one program in JavaScript that does not rely on ProcessingJS at all but instead uses only `setInterval` to sequence events.  It isn't really a game with an event loop though - it's a song player that plays a sequence of notes using the WebAudio API.  But, this is still a recursive function and not a loop
Quack E. Duck
CC BY-SA 4.0
2023-07-05T20:16:04.780Z
@Bbrk24 Could `Timer` be used to "space out" loop iterations?  I never use `Timer` because it always seemed confusing to me compared to the more familiar `asyncAfter` (I'm much newer to Swift than to JavaScript or Python) but wasn't aware it could be used this way
Quack E. Duck
CC BY-SA 4.0
2023-07-05T20:17:11.840Z
@QuackE.Duck I don't think Timer is precise enough for an event loop, but I've used it before to update a value on-screen twice a second.
Bbrk24
CC BY-SA 4.0
2023-07-05T20:19:39.060Z
@Bbrk24 That's helpful to know, but this question isn't *only* about native asynchronous methods, it's also about whether in theory this could be applied directly to *loops* instead of / in the same way as for functions.  As far as I know, `Timer` is still a function and not a loop.  I'll have to go back and check the documentation
Quack E. Duck
CC BY-SA 4.0
2023-07-05T20:21:34.063Z
@QuackE.Duck It can be a function, but because Objective-C, it can also take a target-selector pair. The only argument to the function is the timer object itself.
Bbrk24
CC BY-SA 4.0
2023-07-05T20:29:31.720Z
@RydwolfPrograms Actually, I'm also having a precision-related issue with the song player program because of `setInterval`. It is close enough for a single track (each note gets specified as a frequency and duration), but doesn't work for playing multi-part harmonies because parts with more, shorter notes lag behind parts with fewer, longer notes.  Because `setInterval` only guarantees a minimum wait time, every time the recursive function runs, it introduces more possible delay and so the different tracks start out synchronized then diverge :(  I still haven't found a solution
Quack E. Duck
CC BY-SA 4.0
2023-07-05T20:30:35.260Z
I have definitely seen things like this. Though in non functional languages at least they tend to written as <function>(<callback>) as in everySoOften(callThis). If you squint with a lambda it look similar.
Bruce Adams
CC BY-SA 4.0
2023-07-06T13:49:16.183Z
Python has an [`async for` loop](https://docs.python.org/3/reference/compound_stmts.html?highlight=async#the-async-for-statement) which consumes an asynchronous iterable. Is this what you're looking for?
kaya3
CC BY-SA 4.0
2023-07-06T15:08:22.837Z
@kaya3-supportthestrike That's close, but when I tried using the loop in the global scope, it gave me the error `'async for' outside async function`.  It seems like the loop itself would have to be inside an async function's scope, just like the solutions to the linked SO question.
Quack E. Duck
<p>There is a language you <em>are</em> aware of that has these loops. JavaScript has a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of" rel="nofollow noreferrer"><code>for await .. of</code> loop construction</a> that expects an async iterator, which uses the same Promise-based async as ordinary <code>await</code>.</p>
<p>For your every-five-seconds example, code might look like this:</p>
<pre class="lang-javascript prettyprint-override"><code>for await (let value of every5()) {
  // do stuff here every 5 seconds
}
async function* every5() {
  while (true) {
    await wait(5);
    yield 1
  }
}
function wait(secs) { ... } // typical Promise delay
</code></pre>
<p>The every5 function is an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function*" rel="nofollow noreferrer">async generator</a>; it produces an output with every <code>yield</code> and the loop gets given that value to do something with or ignore. You can also implement these manually with more precise control; most likely, a (standard) library would provide built-in <code>every(secs)</code>, <code>when(event)</code>, even <code>whileEvery(delay, predicate)</code>, etc functions as applicable and useful to the application domain.</p>
<p>The Promise system is built around functions, so there will be function calls happening behind the scenes. You don’t have to write them in the surface syntax. You can have as many of these going at once as you like and they will interleave as the callback times or events occur.</p>
<hr />
<p>There’s no particular problem with this, and any language with existing async/await of a similar form could graft this in without issue, although they are somewhat more complex. There’s nothing that makes it impossible, just an extra bit of language to design, implement, and learn.</p>
<p>It’s a relatively recent addition to JavaScript, which lives in a world where this sort of event-based asynchronicity is extremely common, so it may not meet the bar for other languages to want to expend work on, though there have been others prior as well. It’s also something you can see idiomatically in some functional languages, where the loop part is the complicated bit.</p>

CC BY-SA 4.0
2023-07-05T20:38:02.510Z
2023-07-06T01:04:35.787Z
2023-07-06T01:04:35.787Z
Michael Homer
CC BY-SA 4.0
2023-07-05T23:57:11.113Z
Yes, your `for await` syntax is something I wasn't aware of and **exactly** the kind of thing I was looking for!  Even this still relies on a separately implemented async function though (`every5()`); so it looks like the answer to "can you have an async loop *instead* of function" is both 'yes' and 'no.'  I gave you +1 when I saw this posted but was waiting to see if any answers got posted for other programming languages before accepting anything.  I think you'll be getting the checkmark too :D
Quack E. Duck
CC BY-SA 4.0
2023-07-06T01:08:04.963Z
@QuackE.Duck Yes, although in reality that function probably comes from a library (or builtin) - I implemented it the long way here for demonstration. A language could build in `while (true, 5)` all the same, it's just probably too specific to make its own loop construct in most cases
Michael Homer
# Built-In Asynchronous Loops (Not Functions) - Do they / could they exist?
Posted by: username_0 on 2023-07-05
When writing a game's event loop, I always rely on a function from an external library, like draw() in ProcessingJS for JavaScript, or .after() from tkinter for Python (or DispatchQueue.main.asyncAfter() from GCD for Swift).
Something like this:
import tkinter as tk
window = tk.Tk()

def eventLoop()
    # Do Stuff Here
    
    window.after(1000//framesPerSecond, eventLoop)

eventLoop()
window.mainloop()

It's called an event loop, but it's actually a function, not a loop. If you tried to implement one as an actual loop, like my very first attempt when I had just started learning programming, it wouldn't work because it would "block" the main thread and not allow any user interaction:
// Faulty Event Loop

while(true) {
    // Do Stuff Here
}

This is the difference between synchronous (the while loop) and asynchronous (all the library functions) execution.  I'm aware that a programming language doesn't have to be multithreaded to allow asynchronous execution, and that there are native ways of designating a function asynchronous (like async/await in JS), but haven't been able to find any equivalent for a loop construction.
The closest I found was this question on StackOverflow: https://stackoverflow.com/questions/39110762/while-loops-using-await-async but the answers to the question suggest wrapping the loop inside an asynchronous function because the loop itself at the global level wouldn't be asynchronous.
But why not?  Why isn't there some syntax such as
// Hypothetical native JS asynchronous loop

async while(true, 5) {
    // Do Stuff Here every 5 seconds
}

that could be used from the global scope to specify an infinite loop with 'spaced-out' iterations that don't block the main thread?  Theoretically, it could work by the same mechanism as async/await but using a loop instead of a function.
Would this be problematic to implement, or are there programming languages I'm not aware of that actually do implement something like this?
**Tags:** implementation loops async
> **Comments:**
> **username_1**: Apple's `Timer` object provides basically this, doesn't it?  
> **username_2**: This is basically just JS's `setInterval` right? It could also just be implemented in any language with `async` by `await`ing a delay at the end of each loop iteration (in fact, most languages that _do_ have `async` probably provide non-blocking `async` versions of `sleep`)  
> **username_0**: @RydwolfPrograms I have written one program in JavaScript that does not rely on ProcessingJS at all but instead uses only `setInterval` to sequence events.  It isn't really a game with an event loop though - it's a song player that plays a sequence of notes using the WebAudio API.  But, this is still a recursive function and not a loop  
> **username_0**: @Bbrk24 Could `Timer` be used to "space out" loop iterations?  I never use `Timer` because it always seemed confusing to me compared to the more familiar `asyncAfter` (I'm much newer to Swift than to JavaScript or Python) but wasn't aware it could be used this way  
> **username_1**: @QuackE.Duck I don't think Timer is precise enough for an event loop, but I've used it before to update a value on-screen twice a second.  
> **username_0**: @Bbrk24 That's helpful to know, but this question isn't *only* about native asynchronous methods, it's also about whether in theory this could be applied directly to *loops* instead of / in the same way as for functions.  As far as I know, `Timer` is still a function and not a loop.  I'll have to go back and check the documentation  
> **username_1**: @QuackE.Duck It can be a function, but because Objective-C, it can also take a target-selector pair. The only argument to the function is the timer object itself.  
> **username_0**: @RydwolfPrograms Actually, I'm also having a precision-related issue with the song player program because of `setInterval`. It is close enough for a single track (each note gets specified as a frequency and duration), but doesn't work for playing multi-part harmonies because parts with more, shorter notes lag behind parts with fewer, longer notes.  Because `setInterval` only guarantees a minimum wait time, every time the recursive function runs, it introduces more possible delay and so the different tracks start out synchronized then diverge :(  I still haven't found a solution  
> **username_3**: I have definitely seen things like this. Though in non functional languages at least they tend to written as <function>(<callback>) as in everySoOften(callThis). If you squint with a lambda it look similar.  
> **username_4**: Python has an [`async for` loop](https://docs.python.org/3/reference/compound_stmts.html?highlight=async#the-async-for-statement) which consumes an asynchronous iterable. Is this what you're looking for?  
> **username_0**: @kaya3-supportthestrike That's close, but when I tried using the loop in the global scope, it gave me the error `'async for' outside async function`.  It seems like the loop itself would have to be inside an async function's scope, just like the solutions to the linked SO question.  
---
## 1 answers
### Answer by username_5 on 2023-07-05. Score: 5 | Accepted answer
There is a language you are aware of that has these loops. JavaScript has a for await .. of loop construction that expects an async iterator, which uses the same Promise-based async as ordinary await.
For your every-five-seconds example, code might look like this:
for await (let value of every5()) {
  // do stuff here every 5 seconds
}
async function* every5() {
  while (true) {
    await wait(5);
    yield 1
  }
}
function wait(secs) { ... } // typical Promise delay

The every5 function is an async generator; it produces an output with every yield and the loop gets given that value to do something with or ignore. You can also implement these manually with more precise control; most likely, a (standard) library would provide built-in every(secs), when(event), even whileEvery(delay, predicate), etc functions as applicable and useful to the application domain.
The Promise system is built around functions, so there will be function calls happening behind the scenes. You don’t have to write them in the surface syntax. You can have as many of these going at once as you like and they will interleave as the callback times or events occur.

There’s no particular problem with this, and any language with existing async/await of a similar form could graft this in without issue, although they are somewhat more complex. There’s nothing that makes it impossible, just an extra bit of language to design, implement, and learn.
It’s a relatively recent addition to JavaScript, which lives in a world where this sort of event-based asynchronicity is extremely common, so it may not meet the bar for other languages to want to expend work on, though there have been others prior as well. It’s also something you can see idiomatically in some functional languages, where the loop part is the complicated bit.
> **Comments:**
> **username_0** (2023-07-05): Yes, your `for await` syntax is something I wasn't aware of and **exactly** the kind of thing I was looking for!  Even this still relies on a separately implemented async function though (`every5()`); so it looks like the answer to "can you have an async loop *instead* of function" is both 'yes' and 'no.'  I gave you +1 when I saw this posted but was waiting to see if any answers got posted for other programming languages before accepting anything.  I think you'll be getting the checkmark too :D  
> **username_5** (2023-07-06): @QuackE.Duck Yes, although in reality that function probably comes from a library (or builtin) - I implemented it the long way here for demonstration. A language could build in `while (true, 5)` all the same, it's just probably too specific to make its own loop construct in most cases  
---
