[dart2wasm,dart2js] Fix setTimeout and setInterval impls in d8 scripts

HTML spec says the timeout argument in `setInterval` and `setTimeout`
will be 0 when negative [1], update our mocked versions in the d8 script
to implement this.

Fixes tests on dart2wasm-linux-d8:

- co19/LibTest/async/Timer/Timer.periodic_A02_t01
- co19/LibTest/async/Timer/Timer_A02_t01

These tests already pass on Firefox and Chrome.

Fixes #54598.

[1]: https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-setinterval-dev
in "Timer initialization steps" step 4: "If timeout is less than 0, then
set timeout to 0."

Change-Id: I716f5942b5dff0fbd5a45c2bb6e0ef2732a5ea67
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/362260
Reviewed-by: Martin Kustermann <kustermann@google.com>
Commit-Queue: Ömer Ağacan <omersa@google.com>
Reviewed-by: Nate Biggs <natebiggs@google.com>
diff --git a/pkg/dart2wasm/bin/run_wasm.js b/pkg/dart2wasm/bin/run_wasm.js
index 6915ff1..857a3ec 100644
--- a/pkg/dart2wasm/bin/run_wasm.js
+++ b/pkg/dart2wasm/bin/run_wasm.js
@@ -126,6 +126,7 @@
   var zeroTimerQueue = [];
 
   function addTimer(f, ms) {
+    ms = Math.max(0, ms);
     var id = timerIdCounter++;
     // A callback can be scheduled at most once.
     console.assert(f.$timerId === undefined);
@@ -284,6 +285,7 @@
   }
 
   function addInterval(f, ms) {
+    ms = Math.max(0, ms);
     var id = timerIdCounter++;
     function repeat() {
       // Reactivate with the same id.
diff --git a/sdk/lib/_internal/js_dev_runtime/private/preambles/d8.js b/sdk/lib/_internal/js_dev_runtime/private/preambles/d8.js
index 21dba16..80382b7 100644
--- a/sdk/lib/_internal/js_dev_runtime/private/preambles/d8.js
+++ b/sdk/lib/_internal/js_dev_runtime/private/preambles/d8.js
@@ -82,6 +82,7 @@
   var zeroTimerQueue = [];
 
   function addTimer(f, ms) {
+    ms = Math.max(0, ms);
     var id = timerIdCounter++;
     f.$timerId = id;
     timerIds[id] = f;
@@ -235,6 +236,7 @@
   }
 
   function addInterval(f, ms) {
+    ms = Math.max(0, ms);
     var id = timerIdCounter++;
     function repeat() {
       // Reactivate with the same id.
diff --git a/sdk/lib/_internal/js_runtime/lib/preambles/d8.js b/sdk/lib/_internal/js_runtime/lib/preambles/d8.js
index 01961d9..83b321d 100644
--- a/sdk/lib/_internal/js_runtime/lib/preambles/d8.js
+++ b/sdk/lib/_internal/js_runtime/lib/preambles/d8.js
@@ -74,6 +74,7 @@
   var zeroTimerQueue = [];
 
   function addTimer(f, ms) {
+    ms = Math.max(0, ms);
     var id = timerIdCounter++;
     f.$timerId = id;
     timerIds[id] = f;
@@ -227,6 +228,7 @@
   }
 
   function addInterval(f, ms) {
+    ms = Math.max(0, ms);
     var id = timerIdCounter++;
     function repeat() {
       // Reactivate with the same id.