0

I have some code to be run:

  • immediately after the input event handler if it's called
  • when this handler would usually be called if it's not.

I noticed that queuing a message with setTimeout in the keydown handler works well.

In this demo, the logged sequence is the one we expect:

  • With a regular input : keydown | input | end
  • When an input is prevented in the keydown handler (try entering the letter 'b') : keydown | end
  • When hitting a key that doesn't trigger an input ('Escape') : keydown | end

So it seems to me that the input event is queued before the keydown event is processed, when we don't really know yet whether there will actually be an input. It's just what I need, but how can I be sure things are actually supposed to be implemented this way?

  • What exactly are you trying to achieve? Your question looks like an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) to me. Maybe there is a simpler solution if you tell us why you want to implement this? – Kaddath Dec 20 '22 at 12:47
  • The firing order is keydown-input, you can rely on that. But, when you paste from the clipboard via the right-button context menu, input fires, and keydown doesn't fire at all. – Teemu Dec 20 '22 at 12:48
  • @Teemu No doubt input fires after keydown fires. But how can we know it fires before the keydown handler is processed? – ghostinpeace Dec 20 '22 at 12:52
  • It never will fire before the current script has been totally executed. JS has only a single thread which runs both, the event queue and script execution. – Teemu Dec 20 '22 at 12:53
  • @Kaddath Depending on what happens in the keydown handler, I may need to ensure that the input handler will be called afterwards. The idea was to set a flag in the keydown handler and unset it in the input handler, so it can be checked at the end of the sequence. – ghostinpeace Dec 20 '22 at 12:58
  • @Teemu I'm not sure what you mean by 'before the current script has been totally executed' and why threads would come into play here. It's about ['keydown' is queued / 'input' is queued / 'keydown' is processed / 'input' is processed (or not)] VS ['keydown' is queued / 'keydown is processed' / 'input' is queued / 'input' is processed]. In practice it's the first, and I just wanted to know whether I could read somewhere something that would make me more confident about this answer. – ghostinpeace Dec 20 '22 at 13:03
  • It's the browser pushing an event to the queue when a user action firing a listened event occurs. Then when the call stack is empty, the events are pulled from the queue. If the user action triggered multiple events, they are ordered by type (when exactly this ordering happens might depend on the implementation), and pushed as records to the call stack, where they're executed and removed. While there are records in the call stack, nothing is done on the event queue. – Teemu Dec 20 '22 at 13:46

0 Answers0