[Question]
  [
Your challenge is to write a program that constantly prompts for input, and when input is given, output that five seconds\* later. However, your program must continue prompting for input during that time.
Since this is a bit confusing, here's a demo.
```
<pre id=x></pre><input id=h onchange='var k=this;(()=>{let a=k.value;setTimeout(_=>document.getElementById("x").innerText+=a+"\n", 5000)})();this.value="";' >
```
(Try typing multiple things into the box and pressing enter.)
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest wins!
\*Anywhere between four and six seconds is fine.
## Definition of "prompting for input"
I'm not really sure how to define "prompting for input" in a way that works across most languages, so here's a couple of ways you can do this:
* Prompt for input in a terminal, recieving it on pressing enter
* Open a dialog box that asks for input
* Record every keypress and output those delayed - see [this fiddle](https://jsfiddle.net/6zegdjfq/) thanks to tsh
If you're not sure, ask. Note that for the first two options, the operation must not block further output.
  
[Answer]
# JavaScript, ~~53~~ ~~51~~ 44 bytes
Now 44 bytes thanks to @DomHasting's suggestion to omit `window.`.
(Records every keypress; keyboard events won't register unless you focus on the opened iframe when you click run)
```
onkeyup=e=>setTimeout(console.log,5e3,e.key)
```
[Answer]
# Minecraft Command Blocks, ~895 bytes
[![enter image description here](https://i.stack.imgur.com/zBY3J.png)](https://i.stack.imgur.com/zBY3J.png)
[![enter image description here](https://i.stack.imgur.com/gZc3s.jpg)](https://i.stack.imgur.com/gZc3s.jpg)
My Java answer I already have on this question is pretty good, but as I do also have some skill with Minecraft redstone, I wondered if there was a decent way to do this in Minecraft, and it turns out there is. Because inputting data into Minecraft programs is never quite easy, but I was able to figure out a decent method for this: input is provided by placing a named Creeper mob in a specific location; output is much simpler, as it is simply read out to the game chat.
## Explanation
This "program" consists of two chains of command blocks, as follows:
```
chain 1:
Repeat block, Always active: data modify entity @e[type=minecraft:creeper,dx=2,dy=1,dz=0,limit=1,sort=nearest] PersistenceRequired set value 1
Chain block, Conditional: tp @e[type=minecraft:creeper,dx=3,dy=1,dz=0,limit=1,sort=nearest] ~1 ~222 ~-1
chain 2:
Impulse block, Needs Redstone: say @e[type=creeper,limit=1,sort=nearest]
Chain block, Unconditional: kill @e[type=creeper,limit=1,sort=nearest]
Chain block, Unconditional: kill @e[type=item]
```
Minecraft command block programs are mainly formed by chaining command blocks, where a start block (of either Impulse or Repeat type) can activate a Chain block its pointing at, and those Chain blocks can activate more Chain blocks, etc.
Chains can be started by either an Impulse or Repeat block, where Impulse blocks trigger once when activated, and then do not trigger again until they are de- and then re-activated, while Repeat blocks trigger every in-game tick while they are activated. both of these blocks can be in either "Always active" or "Needs Redstone" mode, where they are either, respectively, active all the time, or only active when powered by a Redstone signal. Chain blocks also have a conditional feature, where they can be set to only activate if the command of the block that triggered them executed successfully.
The first chain queues up the signal Creeper, with the Repeat block looking continuously for a nearby Creeper and trying to set its PersistenceRequired property to 1 (true). If it succeeds at this, the Conditional Chain block is triggered, which teleports the Creeper up 222 blocks, a distance which I calculated takes almost exactly 5 seconds for it to fall. The first command block is necessary as that property prevents it from despawning, as normally all mobs despawn instantly if they are more than 128 blocks from the player.
This teleport also lines it up so it falls into a tripwire, which provides the Redstone signal that triggers the start of the second chain, which writes the name of the Creeper to chat, kills the Creeper, and then destroys all the items the creeper dropped, as otherwise these would clog up the tripwire and prevent further messages from functioning. There is a pool of water placed under the tripwire to prevent the fall from killing the Creeper, as it needs to stay there long enough for the command block to read its name.
The sign indicates where the Creeper should go, although this positioning is not precise, and is mainly there to fulfill my interpretation of the "prompt for input" requirement.
## Byte Count Calculation and Golfing
Per [consensus](https://codegolf.meta.stackexchange.com/a/9529/111305), MC "program" bytecounts are calculated using the size of the structure block .nbt file needed to contain them, which I have uploaded to dropbox [here](https://www.dropbox.com/s/0fct2gsc6af837d/laggytext.nbt?dl=0), so that you can test it in your own world if you want.
Golfing with structure block files is irritating, as its often not clear what increases or decreases bytecount except through trial and error, and bytecount even seems to vary by a few bytes for identical structures. I have tried a few variations of commands, but the ones here seem to have the lowest bytecount. I have tried to fit the "program" into the smallest possible bounding box, and all air blocks in the program are replaced with structure void blocks. I had the sandstone floor as voids too, but that somehow seemed to be larger, so I returned it to sandstone, although it is possible some other block may reduce the file size. The iron block the tripwire is on can also be any block, as long as it supports the tripwire. The sign also seems to be contributing almost 100 bytes, so if it is judged to be unnecessary for the "prompting user" requirement, it would certainly shave off a good deal.
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 37 bytes
Doesn't work online for obvious reasons!
[@Digital Trauma](https://codegolf.stackexchange.com/users/11259/digital-trauma) correctly pointed out an unnecessary spaces for -1, thanks!
```
while read a;do sleep 5&&echo $a&done
```
[Try it online!](https://tio.run/##S0oszvj/vzwjMydVoSg1MUUh0TolX6E4JzW1QMFUTS01OSNfQSVRLSU/L/X//5LU4hJDLhBpBCaNAQ "Bash – Try It Online")
[Answer]
# [Factor](https://factorcode.org/), 46 bytes
```
[ readln '[ _ print ] 5 seconds later t ] loop
```
Factor has a nice timer vocabulary. `later` Takes a quotation to perform and a duration and calls the quotation after the duration has passed. Since TIO is unsuited for displaying the functionality, here's an animated GIF of running this code in Factor's REPL:
[![enter image description here](https://i.stack.imgur.com/TEW1e.gif)](https://i.stack.imgur.com/TEW1e.gif)
[Answer]
# Java 8, 447 437 404 380 374 278 272 259 219 210 bytes
This is my first code golf, and I'm certain both that I could golf this down more, and that Java is a horrible language for this problem and for golfing in, but for my first try I think this isn't too bad. I tried to golf this in Python, which I'm more familiar with, first, but I simply couldn't get around the non-blocking input restriction in Python.
Edit: Screwing around a lot more I found a much shorter version using threads and waiting instead of my list+timestamp idea for the old one:
```
import java.util.*;class B{static void main(String[]a){Scanner s=new Scanner(System.in);for(;;){String t=s.nextLine();new Thread(()->{try{Thread.sleep(5000);}finally{System.out.println(t);return;}}).start();}}}
```
Edit: -6 bytes, I think I'm solidly addicted to code golfing now.
Edit 2: -13 bytes, realized I could put the whole thing in one class and it'd still work.
Edit 3: -41 bytes from @Clashsoft's excellent idea to use a lambda for the thread class instead.
Edit 4: Apparently the lambda actually means I don't need to extend `Thread` anymore, although I do now need `Thread.sleep()` instead of just `sleep()`
### Old Solution
```
import java.util.*;class A{long t;String s;A(long T,String S){t=T;s=S;}public static void main(String[]a)throws java.io.IOException{List<A>L=new ArrayList<>();Scanner s=new Scanner(System.in);for(;;){if(System.in.available()>0&&s.hasNext()){L.add(new A(System.nanoTime(),s.nextLine()));}if(L.size()>0&&L.get(0).t+5e9<System.nanoTime()){System.out.println(L.remove(0).s);}}}}
```
Edit: -10 bytes from trimming the "public" off Main class declaration and a bit of whitespace.
Edit 2: -33 bytes with a bit more trimming and a better import.
Edit 3: -18 bytes by using System.nanoTime() instead of System.currentTimeMillis(), and -6 by Seggan's suggestion to switch to an interface to drop the public modifier, for total of -24.
Edit 3.5: Pasted the wrong code for edit 3, now showing the correct code (I think, I don't have the actual code or an IDE on hand at the moment) with those changes.
Edit 4: @Neil's suggestion to put it all in one class let me save another six bytes, I think I'm getting close to how far this approach can be golfed in Java, but there could be something more I'm not seeing yet.
[Answer]
# [Rust](https://rust-lang.org), ~~180~~ 127 bytes
```
use std::{io::*,thread::*};fn main(){for s in stdin().lock().lines(){spawn(move||{sleep_ms(5000);println!("{}",s.unwrap())});}}
```
Runs an infinite loop, reads the string and spawns a new thread. After 5s of blocking that thread, it prints it back to the console.
```
use std::{io::*, thread::*};
fn main() {
    for s in stdin().lock().lines() {
        spawn(move || {
            sleep_ms(5000);
            println!("{}", s.unwrap())
        });
    }
}
```
Thanks to Xiretza and the community in #rust matrix server :)
## Old answer
```
use std::*;fn main(){let s=io::stdin();loop{let mut b=String::new();s.read_line(&mut b).unwrap();thread::spawn(move||{thread::sleep(time::Duration::from_secs(5));print!("{b}")});}}
```
Runs an infinite loop, reads the string and spawns a new thread. After 5s of blocking that thread, it prints it back to the console.
```
use std::*;
fn main() {
    let s = io::stdin();
    loop {
        let mut b = String::new();
        s.read_line(&mut b).unwrap();
        thread::spawn(move || {
            thread::sleep(time::Duration::from_secs(5));
            print!("{b}")
        });
    }
}
```
Sadly it's not possible to run such programs in [rust playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&code=use%20std%3A%3A*%3B%0Afn%20main()%20%7B%0A%20%20%20%20let%20s%20%3D%20io%3A%3Astdin()%3B%0A%20%20%20%20loop%20%7B%0A%20%20%20%20%20%20%20%20let%20mut%20b%20%3D%20String%3A%3Anew()%3B%0A%20%20%20%20%20%20%20%20s.read_line(%26mut%20b).unwrap()%3B%0A%20%20%20%20%20%20%20%20thread%3A%3Aspawn(move%20%7C%7C%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20thread%3A%3Asleep(time%3A%3ADuration%3A%3Afrom_secs(5))%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20print!(%22%7Bb%7D%22)%0A%20%20%20%20%20%20%20%20%7D)%3B%0A%20%20%20%20%7D%0A%7D%0A).
Not the best language for code-golf, I know, but just wanted to give it a shot. :)
[Answer]
# Python 63 bytes
```
from threading import*
while 1:Timer(5,print,[input()]).start()
```
Thanks AnttiP for showing me that [Timer](https://docs.python.org/3/library/threading.html#threading.Timer) can directly pass arguments to the callback itself, which cut the solution by 20 bytes.
Thomas Baruchel pointed out a valid criticism of the original recursive solution: that the program would crash after 1000 inputs because of Python's recursion limit. Luckily AnttiP's new design is even shorter without recursion.
[Answer]
## Batch, 63 bytes
```
@set/ps=
@start /b cmd /c"ping -n 6 0.0.0.0>nul&echo %s%"
@%0
```
Explanation: `start /b` runs a command in the background in the same console. `ping` is used for the five second delay between the first and last pings. Note that the string is echoed unquoted so that some shell metacharacters may cause the echo to fail.
[Answer]
# [QBasic](https://en.wikipedia.org/wiki/QBasic), 167 bytes
```
DIM d(999),o$(999)
DO
c$=INKEY$
IF""<>c$THEN o$(j)=c$:d(j)=TIMER+5+86400*(TIMER>=86395):j=(j+1)MOD 1E3
IF(INT(TIMER-d(i))=0)*d(i)THEN?o$(i);:d(i)=0:i=(i+1)MOD 1E3
LOOP
```
Runs as an infinite loop; outputs character-by-character. Don't run this unless you have a good way to kill the program. Here's a nicer version that quits when you press Escape:
```
DIM d(999),o$(999)
CLS
DO
c$=INKEY$
IF c$=CHR$(27)THEN END
IF""<>c$THEN o$(j)=c$:d(j)=TIMER+5+86400*(TIMER>=86395):j=(j+1)MOD 1E3
IF(INT(TIMER-d(i))=0)*d(i)THEN?o$(i);:d(i)=0:i=(i+1)MOD 1E3
LOOP
```
You can try it at [Archive.org](https://archive.org/details/msdos_qbasic_megapack).
### Approach
QBasic doesn't have any non-blocking sleep command or multithreading capabilities that I'm aware of, so we're going to go low-tech on this and use `TIMER`, which provides the (floating-point) number of seconds since midnight. When a key is pressed, we store it in the `o$` array, and we also store `TIMER + 5` at the same index in the `d` array. Then we check the first time in `d` to see if it has arrived yet; if so, we output the corresponding character.
Some complexity is added because:
* QBasic has fixed-size arrays rather than lists, so there aren't any pop or push operations. We have to track the index of the next insertion and the index of the next removal, and we have to wrap both around when they reach the size of the array.
* `TIMER` resets at midnight, which breaks the math unless we correct for it.
### Ungolfed
```
CONST ARRAYSIZE = 999
CONST TIMERMAX = 86400  ' Number of seconds in a day
DIM d(ARRAYSIZE)        ' Times at which to output characters
DIM o$(ARRAYSIZE)       ' Characters to output
i = 0                   ' Index of first meaningful entry in d and o$
j = 0                   ' Index just past last meaningful entry in d and o$
' Clear screen
CLS
' Loop forever
DO
  ' If a key is being pressed, store it in c$
  c$ = INKEY$
  ' If it is Esc, quit the program
  IF c$ = CHR$(27) THEN END
  ' For any other key...
  IF c$ <> "" THEN
    ' Store it in o$
    o$(j) = c$
    ' Store 5-seconds-in-the-future time in d
    d(j) = TIMER + 5
    ' Correct for midnight wraparound
    IF d(j) >= TIMERMAX THEN d(j) = d(j) - TIMERMAX
    ' Increment next-entry index
    j = j + 1
    ' Wrap index around if necessary
    IF j > ARRAYSIZE THEN j = 0
  END IF
  ' If we've reached the time for the first character in the array...
  IF d(i) > 0 AND TIMER - d(i) > 0 AND TIMER - d(i) < 1 THEN
    ' Print it without a newline
    PRINT o$(i);
    ' Zero out the time for that character
    d(i) = 0
    ' Increment first-entry index
    i = i + 1
    ' Wrap index around if necessary
    IF i > ARRAYSIZE THEN i = 0
  END IF
LOOP
```
[Answer]
# [Julia](https://julialang.org/), ~~53~~ 42 bytes
```
~_=(r=readline();~@async sleep(5)print(r))
```
[![Demonstration of laggy text editor in Julia](https://i.stack.imgur.com/T5FRx.gif)](https://i.stack.imgur.com/T5FRx.gif)
*-11 bytes thanks to @MarcMush*
Previous version that's perhaps easier to understand at a glance:
```
while 1>0
r=readline()
@async (sleep(5);print(r))
end
```
[Answer]
# C, ~~63~~ ~~62~~ 57 bytes
```
main(b){for(;;){gets(&b);if(fork()){sleep(5);puts(&b);}}}
```
[Try online!](https://tio.run/##LYq7DsMgDAB3f4Wnyh46NI@Jr0mQQ6xQiAJtBsS3U4ZOJ92dfTprW3svGmjlssWLjOHiJCd6rGx0o@4OYi7Ji5w0szk//1hrbe0FA4wwwQwiAnefE8pXAt6ad1zQx@Aw5Us7vB6CedeEMcgP)
Similar to [Amir reza Riahi's answer](https://codegolf.stackexchange.com/a/243654/111351) managed to remove `i` variable and used an 8 byte int buffer.
Shaved off a byte by declaring b as `int b`(instead of `int b[8]`) and by using `&` operator
-5 bytes: `b` is passed in to the main function instead of being declared.
[Answer]
# C, ~~83~~ ~~73~~ 69 bytes
```
main(){for(int i=0;;){char*b;gets(b);if(fork()){sleep(5);puts(b);}}}
```
[Try online!](https://tio.run/##JcpLCoAgEADQ/Zyi5UwQ9HM1dJiU0aQvWivx7Ba0fs80zphS9tkfSMmeAf1xV35qmSmZZQ61Zid3RE3sLX5hRaIUN5ELFfH1/JZzhlI66GGAERSICMAL)
The only problem is that the program should break by ctrl-c and is not terminated by the ctrl-d.
Thanks to Neil, I removed 10 bytes.
[Answer]
# HTML/CSS, 73 72 bytes
I wanted to try solving this without JavaScript, so I came up with this solution. To use it, open it in a browser, press tab, then enter, then start typing and submit a line by pressing enter again. Up to you to decide whether or not this user interaction disqualifies the answer.
```
<p contenteditable><style>p>:last-child{font:0 a}*{transition:5s steps(1
```
## Demo
Note that this demo has to close off the CSS for it to work as a code snippet - this is not necessary when opening the HTML by itself in a browser.
```
<p contenteditable><style>p>:last-child{font:0 a}*{transition:5s steps(1)}
```
## Explanation
The `contenteditable` tag makes it possible for the user to edit the DOM text directly. If you've never heard of it before, run `document.body.setAttribute("contenteditable", true)` on random sites and have fun! Since in this case a `<p>` tag is being edited, adding a newline creates a new `<div>` element for each line, which we can use to our advantage in the CSS.
A simplified version of the CSS is pretty self-explanatory:
```
div {
 font: initial; /* implied */
 transition: font 5s steps(1);
}
div:last-child {
 font: 0px Arial;
}
```
The only uncommon part here is the `steps(1)` setting for the transition, which makes the transition go straight from one state to another (instead of fading smoothly).
[Answer]
# TI-Basic (TI-84), ~~76~~ ~~128~~ ~~121~~ 120 [bytes](https://codegolf.meta.stackexchange.com/a/4764/98541)
```
1→X
1→Y
{0→A
Ans→B
While 1
startTmr→ʟB(X
getKey→ʟA(X
X+tanh(Ans→X
If 5≤checkTmr(ʟB(Y
Then
ʟA(Y
Disp sub("ABC.HDEFGMIJKLRNOPQWTSUV.XYZ",5int(Ans/10-4)+5fPart(Ans/5),1
IS>(Y,X
End
End
```
`ʟA` stores the pressed [keycodes](http://tibasicdev.wikidot.com/userinput#toc4), `ʟB` the time at which they were pressed, `X` is the length of the lists, and `Y` the index of the next letter to print. The precision is one second (precision of `startTmr`) so it should be between 4 and 6 seconds delay. `tanh` serves as a `sign` function since `getKey` is big enough (> 41 for letters)
there's no built-in to translate numbers to characters, hence the long line with all the letters (strange ordering to use mod 5 instead of mod 10). I'm pretty sure this can be further goffed by being clever. Outputing the keycodes instead would save 52 bytes (previous solution)
-1 byte: I believe this is the first time I successfully use [`IS>(`](http://tibasicdev.wikidot.com/is) in code golf, which only works because X is always greater than Y
[![Demo with laggy characters](https://i.stack.imgur.com/MgrzS.gif)](https://i.stack.imgur.com/MgrzS.gif)
[Answer]
# **Kotlin, 122 bytes**
```
import kotlinx.coroutines.*;suspend fun main()=coroutineScope{while(true){readLine()?.let{launch{delay(5000);print(it)}}}}
```
Also my first code-golf. Looking forward for tips and advices.
Explanation: main function is suspendable for non-blocking print. Infinite loop is running under CoroutineScope created with [coroutineScope()](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/coroutine-scope.html) function. In infinite loop program constantly reads the prompt with standard function readLine(). Result of readLine() is used under scope function let() in newly created coroutine created with launch() builder, which delays printing for 5 seconds without blocking the next propmt
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 34 bytes
```
f(){ read c;sleep 5&&echo $c&f;};f
```
[Try it online!](https://tio.run/##S0oszvj/P01Ds1qhKDUxRSHZujgnNbVAwVRNLTU5I19BJVktzbrWOu3//0SuJK5krhQA "Bash – Try It Online")
Pretty similar to [Dom Hasting's answer](https://codegolf.stackexchange.com/a/243625/17152), but managed to save 4 bytes by using a function instead of a loop.
Does *not* work correctly on TIO.
[Answer]
# [Seal](https://seallang.netlify.app/), 25 bytes
```
w(1){i=h#l;t{z(5);p(i);}}
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 32 bytes
```
loop{a=gets;fork{sleep 5;$><<a}}
```
Spawns child processes for each timer. They aren't terminated since the program is non-terminating anyways, so if this is ever run it should be followed with a `Process.waitall`.
No TIO link since TIO has static input.
`fork` is not supported on all OSes (most notably Windows), but [it is listed in Ruby documentation](https://ruby-doc.org/core-2.6.2/Process.html#method-c-fork). An alternative solution that works on all OSes is:
```
loop{a=gets;Thread.new(a){sleep 5;$><<_1}}
```
which is 42 characters instead.
[Answer]
# [Scratch](https://scratch.mit.edu/), 168 bytes
[Try it online!](https://scratch.mit.edu/projects/709395019/)  
This takes advantage of a clone storing a variable's value at the time of the clone's creation. Alternatively, 11 blocks.
```
when gf clicked
delete all of[O v
forever
ask()and wait
set[t v]to(answer
create clone of[myself v
when I start as a clone
wait(5)seconds
add(t)to[O v
delete this clone
```
```
when gf clicked            Syntax
delete all of[O v          Clears the output
forever                    Loops code forever
ask()and wait              Prompts user input
set[t v]to(answer          Sets variable 't' to the input
create clone of[myself v   Creates clone
when I start as a clone    Syntax, also ends 'forever' loop
wait(5)seconds             Waits 5 seconds
add(t)to[O v               Adds to the output the value of 't' at the time of the clone's creation
delete this clone          Deletes itself to avoid the 300 clone limit
```
[Answer]
# TI-Basic (TI-89), 117 [bytes](https://codegolf.meta.stackexchange.com/a/4764/98541)
```
Prgm
 {}→g
 g→t
 xscl→x
 x→y
 Loop
  startTmr()→t[x]
  getKey()→g[x]
  x+min(xscl,g[x])→x
  If checkTmr(t[y])≥5 Then
   Disp char(g[y])
   y+xscl→y
  EndIf
 EndLoop
EndPrgm
```
Port of [my answer for the TI-84](https://codegolf.stackexchange.com/a/243743/98541). The TI-Basic of the TI-89 is much more advanced (it has the `char` command and much much more) but the [tokens](http://tibasicdev.wikidot.com/68k:tokenization) are often longer (a literal `1` is stored as 3 bytes, that's why we use `xscl` [2 bytes] instead)
[![demo](https://i.stack.imgur.com/JF3v5.gif)](https://i.stack.imgur.com/JF3v5.gif)
]