1. 8.6 タイマー
    2. 8.7 Microtask queuing
    3. 8.8 ユーザープロンプト
      1. 8.8.1 単純ダイアログ
      2. 8.8.2 印刷

8.6 タイマー

setTimeout()setInterval()メソッドは、著者がタイマーベースのコールバックをスケジュールできるようにする。

handle = self . setTimeout( handler [, timeout [, arguments... ] ] )

WindowOrWorkerGlobalScope/setTimeout

Support in all current engines.

Firefox1+Safari1+Chrome30+
Opera4+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android30+WebView Android4.4+Samsung Internet3.0+Opera Android10.1+

WindowOrWorkerGlobalScope/setTimeout

Support in all current engines.

Firefox1+Safari1+Chrome30+
Opera4+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android30+WebView Android4.4+Samsung Internet3.0+Opera Android10.1+

timeoutミリ秒後にhandlerを実行するためにタイムアウトをスケジュールする。すべてのargumentsは直接handlerに渡される。

handle = self . setTimeout( code [, timeout ] )

timeoutミリ秒後にcodeを実行するためにタイムアウトをスケジュールする。

self . clearTimeout( handle )

WindowOrWorkerGlobalScope/clearTimeout

Support in all current engines.

Firefox1+Safari4+Chrome45+
Opera4+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android45+WebView Android45+Samsung Internet5.0+Opera Android10.1+

WindowOrWorkerGlobalScope/clearTimeout

Support in all current engines.

Firefox1+Safari4+Chrome45+
Opera4+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android45+WebView Android45+Samsung Internet5.0+Opera Android10.1+

Cancels the timeout set with setTimeout() or setInterval() identified by handle.

handle = self . setInterval( handler [, timeout [, arguments... ] ] )

WindowOrWorkerGlobalScope/setInterval

Support in all current engines.

Firefox1+Safari1+Chrome30+
Opera4+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android30+WebView Android4.4+Samsung Internet3.0+Opera Android10.1+

WindowOrWorkerGlobalScope/setInterval

Support in all current engines.

Firefox1+Safari1+Chrome30+
Opera4+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android30+WebView Android4.4+Samsung Internet3.0+Opera Android10.1+

timeoutミリ秒ごとにhandlerを実行するためにタイムアウトをスケジュールする。すべてのargumentsは直接handlerに渡される。

handle = self . setInterval( code [, timeout ] )

timeoutミリ秒ごとにcodeを実行するためにタイムアウトをスケジュールする。

self . clearInterval( handle )

WindowOrWorkerGlobalScope/clearInterval

Support in all current engines.

Firefox1+Safari4+Chrome4+
Opera4+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

WindowOrWorkerGlobalScope/clearInterval

Support in all current engines.

Firefox1+Safari4+Chrome4+
Opera4+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

Cancels the timeout set with setInterval() or setTimeout() identified by handle.

タイマーは入れ子にすることができる。しかし、5つのそのようなネストされたタイマー後に、間隔は少なくとも4ミリ秒であることが強制される。

このAPIは、タイマーがスケジュールどおり正確に動作することを保証しない。CPU負荷やその他のタスクなどによる遅延が予想される。

遅延なく背中合わせに数ミリ秒のタスクを実行するために、飢えたユーザーインターフェイスを避けるために(およびCPUを占有するためのスクリプトを殺すブラウザーを避けるために)ブラウザーに戻って従いつつ、作業を実行する前の簡単なキューの次のタイマー:

function doExpensiveWork() {
  var done = false;
  // ...
  // this part of the function takes up to five milliseconds
  // set done to true if we're done
  // ...
  return done;
}

function rescheduleWork() {
  var handle = setTimeout(rescheduleWork, 0); // preschedule next iteration
  if (doExpensiveWork())
    clearTimeout(handle); // clear the timeout if we don't need it
}

function scheduleWork() {
  setTimeout(rescheduleWork, 0);
}

scheduleWork(); // queues a task to do lots of work

8.7 Microtask queuing

WindowOrWorkerGlobalScope/queueMicrotask

Support in all current engines.

Firefox69+Safari12.1+Chrome71+
Opera58+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox AndroidNoSafari iOS12.2+Chrome Android71+WebView Android71+Samsung Internet10.0+Opera Android50+
self . queueMicrotask(callback)

Queues a microtask to run the given callback.

The queueMicrotask() method allows authors to schedule a callback on the microtask queue. This allows their code to run after the currently-executing task has run to completion and the JavaScript execution context stack is empty, but without yielding control back to the event loop, as would be the case when using, for example, setTimeout(f, 0).

Authors ought to be aware that scheduling a lot of microtasks has the same performance downsides as running a lot of synchronous code. Both will prevent the browser from doing its own work, such as rendering or scrolling. In many cases, requestAnimationFrame() or requestIdleCallback() is a better choice. In particular, if the goal is to run code before the next rendering cycle, that is the purpose of requestAnimationFrame().

As can be seen from the following examples, the best way of thinking about queueMicrotask() is as a mechanism for rearranging synchronous code, effectively placing the queued code immediately after the current task's worth of non-queued JavaScript.

The most common reason for using queueMicrotask() is to create consistent ordering, even in the cases where information is available synchronously, without introducing undue delay.

For example, consider a custom element firing a load event, that also maintains an internal cache of previously-loaded data. A naïve implementation might look like:

MyElement.prototype.loadData = function (url) {
  if (this._cache[url]) {
    this._setData(this._cache[url]);
    this.dispatchEvent(new Event("load"));
  } else {
    fetch(url).then(res => res.arrayBuffer()).then(data => {
      this._cache[url] = data;
      this._setData(data);
      this.dispatchEvent(new Event("load"));
    });
  }
};

This naïve implementation is problematic, however, in that it causes its users to experience inconsistent behavior. For example, code such as

element.addEventListener("load", () => console.log("loaded"));
console.log("1");
element.loadData();
console.log("2");

will sometimes log "1, 2, loaded" (if the data needs to be fetched), and sometimes log "1, loaded, 2" (if the data is already cached). Similarly, after the call to loadData(), it will be inconsistent whether or not the data is set on the element.

To get a consistent ordering, queueMicrotask() can be used:

MyElement.prototype.loadData = function (url) {
  if (this._cache[url]) {
    queueMicrotask(() => {
      this._setData(this._cache[url]);
      this.dispatchEvent(new Event("load"));
    });
  } else {
    fetch(url).then(res => res.arrayBuffer()).then(data => {
      this._cache[url] = data;
      this._setData(data);
      this.dispatchEvent(new Event("load"));
    });
  }
};

By essentially rearranging the queued code to be after the currently-executing task, this ensures a consistent ordering and update of the element's state.

Another interesting use of queueMicrotask() is to allow uncoordinated "batching" of work by multiple callers. For example, consider a library function that wants to send data somewhere as soon as possible, but doesn't want to make multiple network requests if doing so is easily avoidable. One way to balance this would be like so:

const queuedToSend = [];

function sendData(data) {
  queuedToSend.push(data);

  if (queuedToSend.length === 1) {
    queueMicrotask(() => {
      const stringToSend = JSON.stringify(queuedToSend);
      queuedToSend.length = 0;

      fetch("/endpoint", stringToSend);
    });
  }
}

With this architecture, multiple subsequent calls to sendData() within the same turn of the event loop will be batched together into one fetch() call, but with no intervening event loop tasks preempting the fetch (as would have happened with similar code that instead used setTimeout()).

8.8 ユーザープロンプト

8.8.1 単純ダイアログ

window . alert(message)

Window/alert

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

指定されたメッセージを持つモーダルアラートを表示し、それを命令するユーザーに対して待機する。

result = window . confirm(message)

Window/confirm

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

与えられたメッセージとともにモーダルOK/Cancelプロンプトを表示し、それを命令するユーザーに対して待機し、ユーザーがOKをクリックした場合はtrueを返し、ユーザーがCancelをクリックする場合はfalseを返す。

result = window . prompt(message [, default] )

Window/prompt

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

与えられたメッセージとともにモーダルテキストコントロールプロンプトを表示し、ユーザーがそれを閉じるのを待ち、ユーザーが入力した値を返す。ユーザーがプロンプトをキャンセルした場合、代わりにnullを返す。2番目の引数が存在する場合、指定された値がデフォルトとして使用される。

メディアデータを読み込むメディア要素のような、タスクまたはマイクロタスクに依存するロジックは、このメソッドが発動されるときに延期される。

8.8.2 印刷

Window/print

Support in all current engines.

Firefox1+Safari1.1+Chrome1+
Opera6+Edge79+
Edge (Legacy)12+Internet Explorer5+
Firefox AndroidNoSafari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+
caniuse.com table
window . print()

ページを印刷するようユーザーに指示する。