11cb0ef41Sopenharmony_ci'use strict';
21cb0ef41Sopenharmony_ci
31cb0ef41Sopenharmony_ciconst common = require('../common');
41cb0ef41Sopenharmony_ciconst assert = require('assert');
51cb0ef41Sopenharmony_ci
61cb0ef41Sopenharmony_ciconst immediate = setImmediate(() => {});
71cb0ef41Sopenharmony_ciassert.strictEqual(immediate.hasRef(), true);
81cb0ef41Sopenharmony_ciimmediate.unref();
91cb0ef41Sopenharmony_ciassert.strictEqual(immediate.hasRef(), false);
101cb0ef41Sopenharmony_ciclearImmediate(immediate);
111cb0ef41Sopenharmony_ci
121cb0ef41Sopenharmony_ci// This immediate should execute as it was unrefed and refed again.
131cb0ef41Sopenharmony_ci// It also confirms that unref/ref are chainable.
141cb0ef41Sopenharmony_cisetImmediate(common.mustCall(firstStep)).ref().unref().unref().ref();
151cb0ef41Sopenharmony_ci
161cb0ef41Sopenharmony_cifunction firstStep() {
171cb0ef41Sopenharmony_ci  // Unrefed setImmediate executes if it was unrefed but something else keeps
181cb0ef41Sopenharmony_ci  // the loop open
191cb0ef41Sopenharmony_ci  setImmediate(common.mustCall()).unref();
201cb0ef41Sopenharmony_ci  setTimeout(common.mustCall(() => { setImmediate(secondStep); }), 0);
211cb0ef41Sopenharmony_ci}
221cb0ef41Sopenharmony_ci
231cb0ef41Sopenharmony_cifunction secondStep() {
241cb0ef41Sopenharmony_ci  // clearImmediate works just fine with unref'd immediates
251cb0ef41Sopenharmony_ci  const immA = setImmediate(() => {
261cb0ef41Sopenharmony_ci    clearImmediate(immA);
271cb0ef41Sopenharmony_ci    clearImmediate(immB);
281cb0ef41Sopenharmony_ci    // This should not keep the event loop open indefinitely
291cb0ef41Sopenharmony_ci    // or do anything else weird
301cb0ef41Sopenharmony_ci    immA.ref();
311cb0ef41Sopenharmony_ci    immB.ref();
321cb0ef41Sopenharmony_ci  }).unref();
331cb0ef41Sopenharmony_ci  const immB = setImmediate(common.mustNotCall()).unref();
341cb0ef41Sopenharmony_ci  setImmediate(common.mustCall(finalStep));
351cb0ef41Sopenharmony_ci}
361cb0ef41Sopenharmony_ci
371cb0ef41Sopenharmony_cifunction finalStep() {
381cb0ef41Sopenharmony_ci  // This immediate should not execute as it was unrefed
391cb0ef41Sopenharmony_ci  // and nothing else is keeping the event loop alive
401cb0ef41Sopenharmony_ci  setImmediate(common.mustNotCall()).unref();
411cb0ef41Sopenharmony_ci}
42