# Laggy text editor

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 , 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 thanks to tsh

If you're not sure, ask. Note that for the first two options, the operation must not block further output.

• Can we assume input consists of printable ASCII? Mar 3 at 19:20
• How accurate does "five seconds later" need to be? Is it okay if the delay is inconsistent but is always somewhere between four and six seconds? Mar 3 at 19:58
• @DLosc Yes, you can assume that, and between four and six seconds sounds reasonable. Mar 4 at 3:07
• Is there a maximum length for the input? Can we hard code the max length of the input? Mar 4 at 16:19

# JavaScript, 5351 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)

• Welcome to Code Golf, and nice first answer! Mar 3 at 20:34
• Welcome! I think you can omit window. to save some bytes as well! Mar 3 at 21:43
• @DomHastings that's right! Not sure why I thought window was necessary; I first wrote document.
– code
Mar 3 at 21:46

# Bash, 37 bytes

Doesn't work online for obvious reasons!

@Digital Trauma correctly pointed out an unnecessary spaces for -1, thanks!

while read a;do sleep 5&&echo $a&done  Try it online! • I think you don't need the space in & done Mar 3 at 23:48 • @DigitalTrauma Not sure why I didn't try that! Thank you! Mar 5 at 0:18 # Minecraft Command Blocks, ~895 bytes 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, 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, 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. • Not a huge Minecraft person but I upvoted this just because it's made with Minecraft. – code Mar 12 at 5:11 # Factor, 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: # Java 8, 447437404380374278272259219 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. • Welcome to Code Golf, and nice answer! You might want to check out Tips for golfing in Java, there might be some useful stuff there Mar 4 at 1:04 • Thanks @RadvylfPrograms! I did already look through that page a bit and pulled some tips out of it (like the for(;;) instead of while(true)), but I'll definitely take a more thorough look at it when I'm a bit more awake than I am right now, I'll bet I'll be able to slim a bit more of this beast. Mar 4 at 1:07 • You can use interface A{static void main(String[]a) instead of class Main{public static void main(String[]a) Mar 4 at 2:23 • @Seggan good one, thanks! Mar 4 at 3:01 • You don't need the class B, you can pass a Runnable lambda to the Thread constructor -- ...String t=s.nextLine();new Thread(()->{try{sleep(5000);}finally{System.out.println(t);}}).start();... Mar 5 at 23:23 # Rust, 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. Not the best language for code-golf, I know, but just wanted to give it a shot. :) • Welcome to Code Golf, nice to see Rust here. You can shave 8 bytes writing io::stdin() directly instead of making a variable Mar 4 at 12:17 # Python 63 bytes from threading import* while 1:Timer(5,print,[input()]).start()  Thanks AnttiP for showing me that 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. • This is a good lesson for us python coders. Mar 5 at 5:42 • @graffe why????????????????????????????????????? Mar 5 at 12:37 • You clever use of threading! Mar 5 at 18:58 • oh wow nice python answer! I was trying to get python to work myself, but I guess I didnt know of the threading library. Really love the elegant recursion here Mar 6 at 2:13 • @theonlygusti Hmm, annoying. It can be fixed with from threading import* while 1:Timer(1,print,[input()]).start() Mar 6 at 16:47 # 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. ### 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.

• 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  • Is this a code snippet from the original Microsoft Windows keyboard driver? Mar 4 at 9:43 # Julia, 53 42 bytes ~_=(r=readline();~@async sleep(5)print(r))  -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  • Wouldn't show be better since it's 1 character less than print? Or would that go against the challenge since that's printing extra characters in the output? Mar 5 at 3:24 • Yeah, it would be 1 byte less and I considered it, but I just like the output being exactly what we typed, and don't consider the 1 byte saving worth it. Whether it is allowed in the challenge is up to the OP, but I suspect they'll allow it if someone asks in the question comments. Mar 5 at 3:50 • 42 bytes as a function: !_=(r=readline();!@async sleep(5)print(r)) Mar 6 at 1:00 ## 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. # C, 6362 57 bytes main(b){for(;;){gets(&b);if(fork()){sleep(5);puts(&b);}}}  Try online! Similar to Amir reza Riahi's answer 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. • Welcome to Code Golf, and nice first answer! Mar 6 at 12:25 • @pxeger Thank you. Mar 6 at 15:29 # TI-Basic (TI-84), 76 128 121 120 bytes 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, ʟ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>( in code golf, which only works because X is always greater than Y # 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() 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 • Welcome to Code Golf! If you haven't already, you might want to check out Tips for golfing in Kotlin. Mar 4 at 14:51 • I dont know much about kotlin, but if it accepts scientific notation for numbers you might be able to use delay(5e3) instead of delay(5000) to shave off a byte Mar 6 at 2:15 # C, 8373 69 bytes main(){for(int i=0;;){char*b;gets(b);if(fork()){sleep(5);puts(b);}}}  Try online! 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. • gets needs a buffer in which to read the input, so you can't use it with an uninitialised char*. Furthermore, you need a new buffer for every line, otherwise you just output the same buffer each time. But you can at least remove the j variable and just use if(fork()) instead. – Neil Mar 4 at 15:42 • You would have to ask the question setter whether you can hard code the maximum length. For what you're doing I would probably just use malloc to create the buffer. – Neil Mar 4 at 15:50 • You're not actually using the int i=0 are you? Another 7 bytes bite the dust in that case. – Neil Mar 4 at 21:00 • Ah, so what it's doing is moving the memory for b to somewhere that happens to point to more memory where gets can write. Very lucky! – Neil Mar 4 at 21:06 • I can't explain it in a comment, but try searching for "stack frames". – Neil Mar 5 at 0:34 # Bash, 34 bytes f(){ read c;sleep 5&&echo$c&f;};f


Try it online!

Pretty similar to Dom Hasting's answer, but managed to save 4 bytes by using a function instead of a loop.

Does not work correctly on TIO.

# Seal, 25 bytes

w(1){i=h#l;t{z(5);p(i);}}


# 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).

• I think you can save one byte if you remove the space after transition: Mar 6 at 19:56

# Ruby, 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. An alternative solution that works on all OSes is: loop{a=gets;Thread.new(a){sleep 5;$><<_1}}


# Scratch, 168 bytes

Try it online!
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
create clone of[myself v
when I start as a clone
wait(5)seconds
delete this clone

when gf clicked            Syntax
delete all of[O v          Clears the output
forever                    Loops code forever
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


# TI-Basic (TI-89), 117 bytes

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. The TI-Basic of the TI-89 is much more advanced (it has the char command and much much more) but the tokens are often longer (a literal 1 is stored as 3 bytes, that's why we use xscl [2 bytes] instead)