Bug 163845 - Promise - MutationObserver interaction spins the event loop
Summary: Promise - MutationObserver interaction spins the event loop
Status: RESOLVED WORKSFORME
Alias: None
Product: WebKit
Classification: Unclassified
Component: JavaScriptCore (show other bugs)
Version: Safari Technology Preview
Hardware: Mac OS X 10.11
: P2 Normal
Assignee: Nobody
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2016-10-22 04:01 PDT by Miklos Bertalan
Modified: 2019-11-22 22:33 PST (History)
5 users (show)

See Also:


Attachments
Script to recreate the bug (524 bytes, text/html)
2016-10-22 04:02 PDT, Miklos Bertalan
no flags Details

Note You need to log in before you can comment on or make changes to this bug.
Description Miklos Bertalan 2016-10-22 04:01:22 PDT
Queueing a Promise from a MutationObserver handler or triggering an observed change from a Promise callback spins the event loop. According to the spec, it should register a new microtask and not a new task.

Code to reproduce (it is also attached):

<div class="tester"></div>
<script>
const tester = document.querySelector('.tester')
let counter = 0

setTimeout(() => console.log('timeout'))

new MutationObserver(() => {
  console.log('mutation')
  if (counter < 100) {
    Promise.resolve().then(() => {
      console.log('promise')
      tester.setAttribute('data-random', Math.random())
    })
  }
  counter++
}).observe(tester, {attributes: true})

tester.setAttribute('data-random', Math.random())
</script>

Issue:

It the above code should print: mutation, promise, mutation, promise, ... timeout
Instead it prints: mutation, timeout, promise, mutation, promise, mutation, ...

Notes:

It seems to get it wrong consistently (not just some of the time). I think it is not caused by any kind of throttling.
It seems to queue a new task for both directions (Promise -> Mutation, Mutation -> Promise).
(Promise -> Promise) and (Mutation -> Mutation) are both handled correctly as new microtasks.
Comment 1 Miklos Bertalan 2016-10-22 04:02:26 PDT
Created attachment 292494 [details]
Script to recreate the bug
Comment 2 Ryosuke Niwa 2019-11-22 22:33:51 PST
This appears to be fixed now.