Bug 1404198: Part 2i - Switch to NS_NewTimer* in dom. r=njn
authorKris Maglione <maglione.k@gmail.com>
Sun, 15 Oct 2017 23:15:40 -0700
changeset 386553 e405a4ec473c3d510047fff16599a5f73a8d600b
parent 386552 247d3966c7ac1220c39a86b31b8a98bfbc4895fe
child 386554 33b50e69601405149cb7100a8bd774a2bad035a6
push id32695
push userarchaeopteryx@coole-files.de
push dateTue, 17 Oct 2017 09:45:44 +0000
treeherdermozilla-central@0d9c6250f99d [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersnjn
bugs1404198
milestone58.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 1404198: Part 2i - Switch to NS_NewTimer* in dom. r=njn MozReview-Commit-ID: 8Oei6TuXNbu
dom/base/ChromeUtils.cpp
dom/base/EventSource.cpp
dom/base/Selection.cpp
dom/base/TimeoutExecutor.cpp
dom/base/TimeoutManager.cpp
dom/base/nsContentSink.cpp
dom/base/nsGlobalWindow.cpp
dom/base/nsJSEnvironment.cpp
dom/base/nsWindowMemoryReporter.cpp
dom/canvas/WebGLContextLossHandler.cpp
dom/events/EventStateManager.cpp
dom/events/WheelHandlingHelper.cpp
dom/file/FileReader.cpp
dom/file/nsHostObjectProtocolHandler.cpp
dom/flyweb/FlyWebService.cpp
dom/gamepad/windows/WindowsGamepad.cpp
dom/geolocation/MLSFallback.cpp
dom/geolocation/nsGeolocation.cpp
dom/html/HTMLMediaElement.cpp
dom/html/nsHTMLDNSPrefetch.cpp
dom/indexedDB/ActorsParent.cpp
dom/indexedDB/IndexedDatabaseManager.cpp
dom/ipc/ContentChild.cpp
dom/ipc/ContentParent.cpp
dom/ipc/ProcessPriorityManager.cpp
dom/media/CanvasCaptureMediaStream.cpp
dom/media/ChannelMediaDecoder.cpp
dom/media/MediaDevices.cpp
dom/media/MediaStreamGraph.cpp
dom/media/MediaTimer.cpp
dom/media/VideoUtils.cpp
dom/media/doctor/DecoderDoctorDiagnostics.cpp
dom/media/eme/MediaKeySystemAccessManager.cpp
dom/media/gmp/GMPTimerParent.cpp
dom/media/webrtc/MediaEngineDefault.cpp
dom/media/webrtc/MediaEngineTabVideoSource.cpp
dom/media/webspeech/recognition/SpeechRecognition.cpp
dom/plugins/base/nsNPAPIPluginInstance.cpp
dom/plugins/base/nsNPAPIPluginStreamListener.cpp
dom/plugins/base/nsPluginHost.cpp
dom/plugins/base/nsPluginInstanceOwner.cpp
dom/presentation/PresentationSessionInfo.cpp
dom/presentation/provider/MulticastDNSDeviceProvider.cpp
dom/quota/ActorsParent.cpp
dom/storage/StorageObserver.cpp
dom/workers/RuntimeService.cpp
dom/workers/ServiceWorkerManager.cpp
dom/workers/ServiceWorkerPrivate.cpp
dom/workers/WorkerPrivate.cpp
dom/xbl/nsBindingManager.cpp
dom/xhr/XMLHttpRequestMainThread.cpp
--- a/dom/base/ChromeUtils.cpp
+++ b/dom/base/ChromeUtils.cpp
@@ -314,21 +314,19 @@ namespace {
       SetDeadline(TimeStamp::Now());
       return Run();
     }
 
     void SetTimer(uint32_t aDelay, nsIEventTarget* aTarget) override
     {
       MOZ_ASSERT(aTarget);
       MOZ_ASSERT(!mTimer);
-      mTimer = do_CreateInstance(NS_TIMER_CONTRACTID);
-      if (mTimer) {
-        mTimer->SetTarget(aTarget);
-        mTimer->InitWithCallback(this, aDelay, nsITimer::TYPE_ONE_SHOT);
-      }
+      NS_NewTimerWithCallback(getter_AddRefs(mTimer),
+                              this, aDelay, nsITimer::TYPE_ONE_SHOT,
+                              aTarget);
     }
 
   protected:
     virtual ~IdleDispatchRunnable()
     {
       CancelTimer();
     }
 
--- a/dom/base/EventSource.cpp
+++ b/dom/base/EventSource.cpp
@@ -1197,17 +1197,17 @@ EventSourceImpl::SetReconnectionTimeout(
 {
   AssertIsOnMainThread();
   if (IsClosed()) {
     return NS_ERROR_ABORT;
   }
 
   // the timer will be used whenever the requests are going finished.
   if (!mTimer) {
-    mTimer = do_CreateInstance("@mozilla.org/timer;1");
+    mTimer = NS_NewTimer();
     NS_ENSURE_STATE(mTimer);
   }
 
   nsresult rv = mTimer->InitWithNamedFuncCallback(
     TimerCallback,
     this,
     mReconnectionTime,
     nsITimer::TYPE_ONE_SHOT,
--- a/dom/base/Selection.cpp
+++ b/dom/base/Selection.cpp
@@ -172,23 +172,21 @@ public:
 
     // Store the presentation context. The timer will be
     // stopped by the selection if the prescontext is destroyed.
     mPresContext = aPresContext;
 
     mContent = nsIPresShell::GetCapturingContent();
 
     if (!mTimer) {
-      nsresult result;
-      mTimer = do_CreateInstance("@mozilla.org/timer;1", &result);
-      mTimer->SetTarget(
+      mTimer = NS_NewTimer(
         mPresContext->Document()->EventTargetFor(TaskCategory::Other));
 
-      if (NS_FAILED(result)) {
-        return result;
+      if (!mTimer) {
+        return NS_ERROR_OUT_OF_MEMORY;
       }
     }
 
     return mTimer->InitWithCallback(this, mDelay, nsITimer::TYPE_ONE_SHOT);
   }
 
   nsresult Stop()
   {
--- a/dom/base/TimeoutExecutor.cpp
+++ b/dom/base/TimeoutExecutor.cpp
@@ -50,18 +50,18 @@ TimeoutExecutor::ScheduleDelayed(const T
   MOZ_DIAGNOSTIC_ASSERT(mDeadline.IsNull());
   MOZ_DIAGNOSTIC_ASSERT(mMode == Mode::None);
   MOZ_DIAGNOSTIC_ASSERT(!aMinDelay.IsZero() ||
                         aDeadline > (aNow + mAllowedEarlyFiringTime));
 
   nsresult rv = NS_OK;
 
   if (!mTimer) {
-    mTimer = do_CreateInstance("@mozilla.org/timer;1", &rv);
-    NS_ENSURE_SUCCESS(rv, rv);
+    mTimer = NS_NewTimer();
+    NS_ENSURE_TRUE(mTimer, NS_ERROR_OUT_OF_MEMORY);
 
     uint32_t earlyMicros = 0;
     MOZ_ALWAYS_SUCCEEDS(mTimer->GetAllowedEarlyFiringMicroseconds(&earlyMicros));
     mAllowedEarlyFiringTime = TimeDuration::FromMicroseconds(earlyMicros);
   }
 
   // Always call Cancel() in case we are re-using a timer.  Otherwise
   // the subsequent SetTarget() may fail.
--- a/dom/base/TimeoutManager.cpp
+++ b/dom/base/TimeoutManager.cpp
@@ -1304,29 +1304,22 @@ TimeoutManager::MaybeStartThrottleTimeou
   }
 
   MOZ_DIAGNOSTIC_ASSERT(!mThrottleTimeouts);
 
   MOZ_LOG(gLog, LogLevel::Debug,
           ("TimeoutManager %p delaying tracking timeout throttling by %dms\n",
            this, gTimeoutThrottlingDelay));
 
-  mThrottleTimeoutsTimer =
-    do_CreateInstance("@mozilla.org/timer;1");
-  if (!mThrottleTimeoutsTimer) {
-    return;
-  }
-
   nsCOMPtr<nsITimerCallback> callback =
     new ThrottleTimeoutsCallback(&mWindow);
 
-  mThrottleTimeoutsTimer->SetTarget(EventTarget());
-
-  mThrottleTimeoutsTimer->InitWithCallback(
-    callback, gTimeoutThrottlingDelay, nsITimer::TYPE_ONE_SHOT);
+  NS_NewTimerWithCallback(getter_AddRefs(mThrottleTimeoutsTimer),
+                          callback, gTimeoutThrottlingDelay, nsITimer::TYPE_ONE_SHOT,
+                          EventTarget());
 }
 
 void
 TimeoutManager::BeginSyncOperation()
 {
   // If we're beginning a sync operation, the currently running
   // timeout will be put on hold. To not get into an inconsistent
   // state, where the currently running timeout appears to take time
--- a/dom/base/nsContentSink.cpp
+++ b/dom/base/nsContentSink.cpp
@@ -1397,30 +1397,24 @@ nsContentSink::WillInterruptImpl()
         }
       } else if (!mNotificationTimer) {
         interval -= diff;
         int32_t delay = interval;
 
         // Convert to milliseconds
         delay /= PR_USEC_PER_MSEC;
 
-        mNotificationTimer = do_CreateInstance("@mozilla.org/timer;1",
-                                               &result);
-        if (NS_SUCCEEDED(result)) {
+        NS_NewTimerWithCallback(getter_AddRefs(mNotificationTimer),
+                                this, delay,
+                                nsITimer::TYPE_ONE_SHOT);
+        if (mNotificationTimer) {
           SINK_TRACE(static_cast<LogModule*>(gContentSinkLogModuleInfo),
                      SINK_TRACE_REFLOW,
                      ("nsContentSink::WillInterrupt: setting up timer with "
                       "delay %d", delay));
-
-          result =
-            mNotificationTimer->InitWithCallback(this, delay,
-                                                 nsITimer::TYPE_ONE_SHOT);
-          if (NS_FAILED(result)) {
-            mNotificationTimer = nullptr;
-          }
         }
       }
     }
   } else {
     SINK_TRACE(static_cast<LogModule*>(gContentSinkLogModuleInfo),
                SINK_TRACE_REFLOW,
                ("nsContentSink::WillInterrupt: flushing tags "
                 "unconditionally"));
--- a/dom/base/nsGlobalWindow.cpp
+++ b/dom/base/nsGlobalWindow.cpp
@@ -7093,20 +7093,20 @@ FullscreenTransitionTask::Run()
     // 2. the user has switched to another tab before we get here.
     // Completely fixing those cases seems to be tricky, and since they
     // should rarely happen, it probably isn't worth to fix. Hence we
     // simply add a timeout here to ensure we never hang forever.
     // In addition, if the page is complicated or the machine is less
     // powerful, layout could take a long time, in which case, staying
     // in black screen for that long could hurt user experience even
     // more than exposing an intermediate state.
-    mTimer = do_CreateInstance(NS_TIMER_CONTRACTID);
     uint32_t timeout =
       Preferences::GetUint("full-screen-api.transition.timeout", 1000);
-    mTimer->Init(observer, timeout, nsITimer::TYPE_ONE_SHOT);
+    NS_NewTimerWithObserver(getter_AddRefs(mTimer),
+                            observer, timeout, nsITimer::TYPE_ONE_SHOT);
   } else if (stage == eAfterToggle) {
     Telemetry::AccumulateTimeDelta(Telemetry::FULLSCREEN_TRANSITION_BLACK_MS,
                                    mFullscreenChangeStartTime);
     mWidget->PerformFullscreenTransition(nsIWidget::eAfterFullscreenToggle,
                                          mDuration.mFadeOut, mTransitionData,
                                          this);
   } else if (stage == eEnd) {
     PROFILER_ADD_MARKER("Fullscreen transition end");
@@ -12012,18 +12012,18 @@ nsGlobalWindow::RegisterIdleObserver(nsI
   if (mIdleObservers.IsEmpty()) {
     mIdleService = do_GetService("@mozilla.org/widget/idleservice;1", &rv);
     NS_ENSURE_SUCCESS(rv, rv);
 
     rv = mIdleService->AddIdleObserver(mObserver, MIN_IDLE_NOTIFICATION_TIME_S);
     NS_ENSURE_SUCCESS(rv, rv);
 
     if (!mIdleTimer) {
-      mIdleTimer = do_CreateInstance(NS_TIMER_CONTRACTID, &rv);
-      NS_ENSURE_SUCCESS(rv, rv);
+      mIdleTimer = NS_NewTimer();
+      NS_ENSURE_TRUE(mIdleTimer, NS_ERROR_OUT_OF_MEMORY);
     } else {
       mIdleTimer->Cancel();
     }
   }
 
   MOZ_ASSERT(mIdleService);
   MOZ_ASSERT(mIdleTimer);
 
--- a/dom/base/nsJSEnvironment.cpp
+++ b/dom/base/nsJSEnvironment.cpp
@@ -2110,59 +2110,47 @@ nsJSContext::PokeGC(JS::gcreason::Reason
 
   if (sICCRunner) {
     // Make sure GC is called after the current CC completes.
     // No need to set sNeedsFullCC because we are currently running a CC.
     sNeedsGCAfterCC = true;
     return;
   }
 
-  CallCreateInstance("@mozilla.org/timer;1", &sGCTimer);
-
-  if (!sGCTimer) {
-    // Failed to create timer (probably because we're in XPCOM shutdown)
-    return;
-  }
-
   static bool first = true;
 
-  sGCTimer->SetTarget(SystemGroup::EventTargetFor(TaskCategory::GarbageCollection));
-  sGCTimer->InitWithNamedFuncCallback(GCTimerFired,
-                                      reinterpret_cast<void *>(aReason),
-                                      aDelay
-                                      ? aDelay
-                                      : (first
-                                         ? NS_FIRST_GC_DELAY
-                                         : NS_GC_DELAY),
-                                      nsITimer::TYPE_ONE_SHOT_LOW_PRIORITY,
-                                      "GCTimerFired");
+  NS_NewTimerWithFuncCallback(&sGCTimer,
+                              GCTimerFired,
+                              reinterpret_cast<void *>(aReason),
+                              aDelay
+                              ? aDelay
+                              : (first
+                                 ? NS_FIRST_GC_DELAY
+                                 : NS_GC_DELAY),
+                              nsITimer::TYPE_ONE_SHOT_LOW_PRIORITY,
+                              "GCTimerFired",
+                              SystemGroup::EventTargetFor(TaskCategory::GarbageCollection));
 
   first = false;
 }
 
 // static
 void
 nsJSContext::PokeShrinkingGC()
 {
   if (sShrinkingGCTimer || sShuttingDown) {
     return;
   }
 
-  CallCreateInstance("@mozilla.org/timer;1", &sShrinkingGCTimer);
-
-  if (!sShrinkingGCTimer) {
-    // Failed to create timer (probably because we're in XPCOM shutdown)
-    return;
-  }
-
-  sShrinkingGCTimer->SetTarget(SystemGroup::EventTargetFor(TaskCategory::GarbageCollection));
-  sShrinkingGCTimer->InitWithNamedFuncCallback(ShrinkingGCTimerFired, nullptr,
-                                               sCompactOnUserInactiveDelay,
-                                               nsITimer::TYPE_ONE_SHOT_LOW_PRIORITY,
-                                               "ShrinkingGCTimerFired");
+  NS_NewTimerWithFuncCallback(&sShrinkingGCTimer,
+                              ShrinkingGCTimerFired, nullptr,
+                              sCompactOnUserInactiveDelay,
+                              nsITimer::TYPE_ONE_SHOT_LOW_PRIORITY,
+                              "ShrinkingGCTimerFired",
+                              SystemGroup::EventTargetFor(TaskCategory::GarbageCollection));
 }
 
 // static
 void
 nsJSContext::MaybePokeCC()
 {
   if (sCCRunner || sICCRunner || sShuttingDown || !sHasRunGC) {
     return;
@@ -2330,23 +2318,23 @@ DOMGCSliceCallback(JSContext* aCx, JS::G
       sLikelyShortLivingObjectsNeedingGC = 0;
       sCleanupsSinceLastGC = 0;
       sNeedsFullCC = true;
       sHasRunGC = true;
       nsJSContext::MaybePokeCC();
 
       if (aDesc.isZone_) {
         if (!sFullGCTimer && !sShuttingDown) {
-          CallCreateInstance("@mozilla.org/timer;1", &sFullGCTimer);
-          sFullGCTimer->SetTarget(SystemGroup::EventTargetFor(TaskCategory::GarbageCollection));
-          sFullGCTimer->InitWithNamedFuncCallback(FullGCTimerFired,
-                                                  nullptr,
-                                                  NS_FULL_GC_DELAY,
-                                                  nsITimer::TYPE_ONE_SHOT_LOW_PRIORITY,
-                                                  "FullGCTimerFired");
+          NS_NewTimerWithFuncCallback(&sFullGCTimer,
+                                      FullGCTimerFired,
+                                      nullptr,
+                                      NS_FULL_GC_DELAY,
+                                      nsITimer::TYPE_ONE_SHOT_LOW_PRIORITY,
+                                      "FullGCTimerFired",
+                                      SystemGroup::EventTargetFor(TaskCategory::GarbageCollection));
         }
       } else {
         nsJSContext::KillFullGCTimer();
       }
 
       if (ShouldTriggerCC(nsCycleCollector_suspectedCount())) {
         nsCycleCollector_dispatchDeferredDeletion();
       }
--- a/dom/base/nsWindowMemoryReporter.cpp
+++ b/dom/base/nsWindowMemoryReporter.cpp
@@ -822,23 +822,20 @@ nsWindowMemoryReporter::AsyncCheckForGho
   // If more than kTimeBetweenChecks seconds have elapsed since the last check,
   // timerDelay is 0.  Otherwise, it is kTimeBetweenChecks, reduced by the time
   // since the last check.  Reducing the delay by the time since the last check
   // prevents the timer from being completely starved if it is repeatedly killed
   // and restarted.
   int32_t timeSinceLastCheck = (TimeStamp::NowLoRes() - mLastCheckForGhostWindows).ToSeconds();
   int32_t timerDelay = (kTimeBetweenChecks - std::min(timeSinceLastCheck, kTimeBetweenChecks)) * PR_MSEC_PER_SEC;
 
-  mCheckTimer = do_CreateInstance("@mozilla.org/timer;1");
-
-  if (mCheckTimer) {
-    mCheckTimer->InitWithNamedFuncCallback(CheckTimerFired, nullptr,
-                                           timerDelay, nsITimer::TYPE_ONE_SHOT,
-                                           "nsWindowMemoryReporter::AsyncCheckForGhostWindows_timer");
-  }
+  NS_NewTimerWithFuncCallback(getter_AddRefs(mCheckTimer),
+                              CheckTimerFired, nullptr,
+                              timerDelay, nsITimer::TYPE_ONE_SHOT,
+                              "nsWindowMemoryReporter::AsyncCheckForGhostWindows_timer");
 }
 
 void
 nsWindowMemoryReporter::ObserveAfterMinimizeMemoryUsage()
 {
   // Someone claims they've done enough GC/CCs so that all eligible windows
   // have been free'd.  So we deem that any windows which satisfy ghost
   // criteria (1) and (2) now satisfy criterion (3) as well.
--- a/dom/canvas/WebGLContextLossHandler.cpp
+++ b/dom/canvas/WebGLContextLossHandler.cpp
@@ -44,17 +44,17 @@ private:
 };
 
 NS_IMPL_ISUPPORTS(WatchdogTimerEvent, nsITimerCallback, nsINamed)
 
 ////////////////////////////////////////
 
 WebGLContextLossHandler::WebGLContextLossHandler(WebGLContext* webgl)
     : mWebGL(webgl)
-    , mTimer(do_CreateInstance(NS_TIMER_CONTRACTID))
+    , mTimer(NS_NewTimer())
     , mTimerPending(false)
     , mShouldRunTimerAgain(false)
 #ifdef DEBUG
     , mEventTarget(GetCurrentThreadSerialEventTarget())
 #endif
 {
     MOZ_ASSERT(mEventTarget);
 }
--- a/dom/events/EventStateManager.cpp
+++ b/dom/events/EventStateManager.cpp
@@ -314,21 +314,18 @@ EventStateManager::EventStateManager()
 
 nsresult
 EventStateManager::UpdateUserActivityTimer()
 {
   if (!gUserInteractionTimerCallback)
     return NS_OK;
 
   if (!gUserInteractionTimer) {
-    CallCreateInstance("@mozilla.org/timer;1", &gUserInteractionTimer);
-    if (gUserInteractionTimer) {
-      gUserInteractionTimer->SetTarget(
-        SystemGroup::EventTargetFor(TaskCategory::Other));
-    }
+    gUserInteractionTimer = NS_NewTimer(
+      SystemGroup::EventTargetFor(TaskCategory::Other)).take();
   }
 
   if (gUserInteractionTimer) {
     gUserInteractionTimer->InitWithCallback(gUserInteractionTimerCallback,
                                             NS_USER_INTERACTION_INTERVAL,
                                             nsITimer::TYPE_ONE_SHOT);
   }
   return NS_OK;
@@ -1449,28 +1446,25 @@ EventStateManager::CreateClickHoldTimer(
                                         nsGkAtoms::popup))
       return;
 
     // check for a <menubutton> like bookmarks
     if (mGestureDownContent->IsXULElement(nsGkAtoms::menubutton))
       return;
   }
 
-  mClickHoldTimer = do_CreateInstance("@mozilla.org/timer;1");
-  if (mClickHoldTimer) {
-    int32_t clickHoldDelay =
-      Preferences::GetInt("ui.click_hold_context_menus.delay", 500);
-    mClickHoldTimer->SetTarget(SystemGroup::EventTargetFor(TaskCategory::Other));
-    mClickHoldTimer->InitWithNamedFuncCallback(
-      sClickHoldCallback,
-      this,
-      clickHoldDelay,
-      nsITimer::TYPE_ONE_SHOT,
-      "EventStateManager::CreateClickHoldTimer");
-  }
+  int32_t clickHoldDelay =
+    Preferences::GetInt("ui.click_hold_context_menus.delay", 500);
+  NS_NewTimerWithFuncCallback(getter_AddRefs(mClickHoldTimer),
+                              sClickHoldCallback,
+                              this,
+                              clickHoldDelay,
+                              nsITimer::TYPE_ONE_SHOT,
+                              "EventStateManager::CreateClickHoldTimer",
+                              SystemGroup::EventTargetFor(TaskCategory::Other));
 } // CreateClickHoldTimer
 
 //
 // KillClickHoldTimer
 //
 // Stop the timer that would show the context menu dead in its tracks
 //
 void
--- a/dom/events/WheelHandlingHelper.cpp
+++ b/dom/events/WheelHandlingHelper.cpp
@@ -319,21 +319,20 @@ WheelTransaction::OnTimeout(nsITimer* aT
                       true, true);
   }
 }
 
 /* static */ void
 WheelTransaction::SetTimeout()
 {
   if (!sTimer) {
-    nsCOMPtr<nsITimer> timer = do_CreateInstance(NS_TIMER_CONTRACTID);
-    if (!timer) {
+    sTimer = NS_NewTimer().take();
+    if (!sTimer) {
       return;
     }
-    timer.swap(sTimer);
   }
   sTimer->Cancel();
   DebugOnly<nsresult> rv =
     sTimer->InitWithNamedFuncCallback(OnTimeout,
                                       nullptr,
                                       GetTimeoutTime(),
                                       nsITimer::TYPE_ONE_SHOT,
                                       "WheelTransaction::SetTimeout");
--- a/dom/file/FileReader.cpp
+++ b/dom/file/FileReader.cpp
@@ -524,17 +524,17 @@ FileReader::WrapObject(JSContext* aCx, J
 {
   return FileReaderBinding::Wrap(aCx, this, aGivenProto);
 }
 
 void
 FileReader::StartProgressEventTimer()
 {
   if (!mProgressNotifier) {
-    mProgressNotifier = do_CreateInstance(NS_TIMER_CONTRACTID);
+    mProgressNotifier = NS_NewTimer();
   }
 
   if (mProgressNotifier) {
     mProgressEventWasDelayed = false;
     mTimerIsActive = true;
     mProgressNotifier->Cancel();
     mProgressNotifier->SetTarget(mTarget);
     mProgressNotifier->InitWithCallback(this, NS_PROGRESS_EVENT_INTERVAL,
--- a/dom/file/nsHostObjectProtocolHandler.cpp
+++ b/dom/file/nsHostObjectProtocolHandler.cpp
@@ -429,28 +429,20 @@ class ReleasingTimerHolder final : publi
 {
 public:
   NS_DECL_ISUPPORTS
 
   static void
   Create(nsTArray<nsWeakPtr>&& aArray)
   {
     RefPtr<ReleasingTimerHolder> holder = new ReleasingTimerHolder(Move(aArray));
-    holder->mTimer = do_CreateInstance(NS_TIMER_CONTRACTID);
-
-    // If we are shutting down, we are not able to create a timer.
-    if (!holder->mTimer) {
-      return;
-    }
-
-    MOZ_ALWAYS_SUCCEEDS(holder->mTimer->SetTarget(
-      SystemGroup::EventTargetFor(TaskCategory::Other)));
-
-    nsresult rv = holder->mTimer->InitWithCallback(holder, RELEASING_TIMER,
-                                                   nsITimer::TYPE_ONE_SHOT);
+    nsresult rv = NS_NewTimerWithCallback(getter_AddRefs(holder->mTimer),
+                                          holder, RELEASING_TIMER,
+                                          nsITimer::TYPE_ONE_SHOT,
+                                          SystemGroup::EventTargetFor(TaskCategory::Other));
     NS_ENSURE_SUCCESS_VOID(rv);
   }
 
   NS_IMETHOD
   Notify(nsITimer* aTimer) override
   {
     for (uint32_t i = 0; i < mURIs.Length(); ++i) {
       nsCOMPtr<nsIURI> uri = do_QueryReferent(mURIs[i]);
--- a/dom/flyweb/FlyWebService.cpp
+++ b/dom/flyweb/FlyWebService.cpp
@@ -665,22 +665,22 @@ FlyWebMDNSService::Notify(nsITimer* time
   return NS_OK;
 }
 
 nsresult
 FlyWebMDNSService::Init()
 {
   MOZ_ASSERT(mDiscoveryState == DISCOVERY_IDLE);
 
-  mDiscoveryStartTimer = do_CreateInstance("@mozilla.org/timer;1");
+  mDiscoveryStartTimer = NS_NewTimer();
   if (!mDiscoveryStartTimer) {
     return NS_ERROR_FAILURE;
   }
 
-  mDiscoveryStopTimer = do_CreateInstance("@mozilla.org/timer;1");
+  mDiscoveryStopTimer = NS_NewTimer();
   if (!mDiscoveryStopTimer) {
     return NS_ERROR_FAILURE;
   }
 
   nsresult rv;
   mDNSServiceDiscovery = do_GetService(DNSSERVICEDISCOVERY_CONTRACT_ID, &rv);
   if (NS_WARN_IF(NS_FAILED(rv))) {
     return rv;
--- a/dom/gamepad/windows/WindowsGamepad.cpp
+++ b/dom/gamepad/windows/WindowsGamepad.cpp
@@ -349,19 +349,19 @@ DirectInputMessageLoopOnceCallback(nsITi
   }
 }
 
 class WindowsGamepadService
 {
  public:
   WindowsGamepadService()
   {
-    mDirectInputTimer = do_CreateInstance("@mozilla.org/timer;1");
-    mXInputTimer = do_CreateInstance("@mozilla.org/timer;1");
-    mDeviceChangeTimer = do_CreateInstance("@mozilla.org/timer;1");
+    mDirectInputTimer = NS_NewTimer();
+    mXInputTimer = NS_NewTimer();
+    mDeviceChangeTimer = NS_NewTimer();
   }
   virtual ~WindowsGamepadService()
   {
     Cleanup();
   }
 
   void DevicesChanged(bool aIsStablizing);
 
--- a/dom/geolocation/MLSFallback.cpp
+++ b/dom/geolocation/MLSFallback.cpp
@@ -23,21 +23,18 @@ MLSFallback::~MLSFallback()
 nsresult
 MLSFallback::Startup(nsIGeolocationUpdate* aWatcher)
 {
   if (mHandoffTimer || mMLSFallbackProvider) {
     return NS_OK;
   }
 
   mUpdateWatcher = aWatcher;
-  nsresult rv;
-  mHandoffTimer = do_CreateInstance("@mozilla.org/timer;1", &rv);
-  NS_ENSURE_SUCCESS(rv, rv);
-  rv = mHandoffTimer->InitWithCallback(this, mDelayMs, nsITimer::TYPE_ONE_SHOT);
-  return rv;
+  return NS_NewTimerWithCallback(getter_AddRefs(mHandoffTimer),
+                                 this, mDelayMs, nsITimer::TYPE_ONE_SHOT);
 }
 
 nsresult
 MLSFallback::Shutdown()
 {
   mUpdateWatcher = nullptr;
 
   if (mHandoffTimer) {
--- a/dom/geolocation/nsGeolocation.cpp
+++ b/dom/geolocation/nsGeolocation.cpp
@@ -517,19 +517,19 @@ nsGeolocationRequest::GetRequester(nsICo
 void
 nsGeolocationRequest::SetTimeoutTimer()
 {
   MOZ_ASSERT(!mShutdown, "set timeout after shutdown");
 
   StopTimeoutTimer();
 
   if (mOptions && mOptions->mTimeout != 0 && mOptions->mTimeout != 0x7fffffff) {
-    mTimeoutTimer = do_CreateInstance("@mozilla.org/timer;1");
     RefPtr<TimerCallbackHolder> holder = new TimerCallbackHolder(this);
-    mTimeoutTimer->InitWithCallback(holder, mOptions->mTimeout, nsITimer::TYPE_ONE_SHOT);
+    NS_NewTimerWithCallback(getter_AddRefs(mTimeoutTimer),
+                            holder, mOptions->mTimeout, nsITimer::TYPE_ONE_SHOT);
   }
 }
 
 void
 nsGeolocationRequest::StopTimeoutTimer()
 {
   if (mTimeoutTimer) {
     mTimeoutTimer->Cancel();
@@ -862,17 +862,17 @@ nsGeolocationService::StartDevice(nsIPri
 
   return NS_OK;
 }
 
 void
 nsGeolocationService::SetDisconnectTimer()
 {
   if (!mDisconnectTimer) {
-    mDisconnectTimer = do_CreateInstance("@mozilla.org/timer;1");
+    mDisconnectTimer = NS_NewTimer();
   } else {
     mDisconnectTimer->Cancel();
   }
 
   mDisconnectTimer->Init(this,
                          sProviderTimeout,
                          nsITimer::TYPE_ONE_SHOT);
 }
--- a/dom/html/HTMLMediaElement.cpp
+++ b/dom/html/HTMLMediaElement.cpp
@@ -4574,22 +4574,21 @@ void HTMLMediaElement::VideoDecodeSuspen
 void HTMLMediaElement::HiddenVideoStart()
 {
   MOZ_ASSERT(NS_IsMainThread());
   mHiddenPlayTime.Start();
   if (mVideoDecodeSuspendTimer) {
     // Already started, just keep it running.
     return;
   }
-  mVideoDecodeSuspendTimer = do_CreateInstance("@mozilla.org/timer;1");
-  mVideoDecodeSuspendTimer->SetTarget(mMainThreadEventTarget);
-  mVideoDecodeSuspendTimer->InitWithNamedFuncCallback(
-    VideoDecodeSuspendTimerCallback, this,
-    MediaPrefs::MDSMSuspendBackgroundVideoDelay(), nsITimer::TYPE_ONE_SHOT,
-    "HTMLMediaElement::VideoDecodeSuspendTimerCallback");
+  NS_NewTimerWithFuncCallback(getter_AddRefs(mVideoDecodeSuspendTimer),
+                              VideoDecodeSuspendTimerCallback, this,
+                              MediaPrefs::MDSMSuspendBackgroundVideoDelay(), nsITimer::TYPE_ONE_SHOT,
+                              "HTMLMediaElement::VideoDecodeSuspendTimerCallback",
+                              mMainThreadEventTarget);
 }
 
 void HTMLMediaElement::HiddenVideoStop()
 {
   MOZ_ASSERT(NS_IsMainThread());
   mHiddenPlayTime.Pause();
   mVideoDecodeSuspendTime.Pause();
   if (!mVideoDecodeSuspendTimer) {
@@ -5783,21 +5782,20 @@ void HTMLMediaElement::ProgressTimerCall
 }
 
 void HTMLMediaElement::StartProgressTimer()
 {
   MOZ_ASSERT(NS_IsMainThread());
   MOZ_ASSERT(mNetworkState == nsIDOMHTMLMediaElement::NETWORK_LOADING);
   NS_ASSERTION(!mProgressTimer, "Already started progress timer.");
 
-  mProgressTimer = do_CreateInstance("@mozilla.org/timer;1");
-  mProgressTimer->SetTarget(mMainThreadEventTarget);
-  mProgressTimer->InitWithNamedFuncCallback(
-    ProgressTimerCallback, this, PROGRESS_MS, nsITimer::TYPE_REPEATING_SLACK,
-    "HTMLMediaElement::ProgressTimerCallback");
+  NS_NewTimerWithFuncCallback(getter_AddRefs(mProgressTimer),
+                              ProgressTimerCallback, this, PROGRESS_MS, nsITimer::TYPE_REPEATING_SLACK,
+                              "HTMLMediaElement::ProgressTimerCallback",
+                              mMainThreadEventTarget);
 }
 
 void HTMLMediaElement::StartProgress()
 {
   // Record the time now for detecting stalled.
   mDataTime = TimeStamp::NowLoRes();
   // Reset mProgressTime so that mDataTime is not indicating bytes received
   // after the last progress event.
--- a/dom/html/nsHTMLDNSPrefetch.cpp
+++ b/dom/html/nsHTMLDNSPrefetch.cpp
@@ -273,17 +273,17 @@ nsHTMLDNSPrefetch::nsListener::OnLookupC
 /////////////////////////////////////////////////////////////////////////////////////////////////////////
 
 nsHTMLDNSPrefetch::nsDeferrals::nsDeferrals()
   : mHead(0),
     mTail(0),
     mActiveLoaderCount(0),
     mTimerArmed(false)
 {
-  mTimer = do_CreateInstance("@mozilla.org/timer;1");
+  mTimer = NS_NewTimer();;
 }
 
 nsHTMLDNSPrefetch::nsDeferrals::~nsDeferrals()
 {
   if (mTimerArmed) {
     mTimerArmed = false;
     mTimer->Cancel();
   }
--- a/dom/indexedDB/ActorsParent.cpp
+++ b/dom/indexedDB/ActorsParent.cpp
@@ -11987,17 +11987,17 @@ DatabaseUpdateFunction::UpdateInternal(i
 }
 
 /*******************************************************************************
  * ConnectionPool implementation
  ******************************************************************************/
 
 ConnectionPool::ConnectionPool()
   : mDatabasesMutex("ConnectionPool::mDatabasesMutex")
-  , mIdleTimer(do_CreateInstance(NS_TIMER_CONTRACTID))
+  , mIdleTimer(NS_NewTimer())
   , mNextTransactionId(0)
   , mTotalThreadCount(0)
   , mShutdownRequested(false)
   , mShutdownComplete(false)
 {
   AssertIsOnOwningThread();
   AssertIsOnBackgroundThread();
   MOZ_ASSERT(mIdleTimer);
--- a/dom/indexedDB/IndexedDatabaseManager.cpp
+++ b/dom/indexedDB/IndexedDatabaseManager.cpp
@@ -383,17 +383,17 @@ IndexedDatabaseManager::Init()
   if (sIsMainProcess) {
     nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
     NS_ENSURE_STATE(obs);
 
     nsresult rv =
       obs->AddObserver(this, DISKSPACEWATCHER_OBSERVER_TOPIC, false);
     NS_ENSURE_SUCCESS(rv, rv);
 
-    mDeleteTimer = do_CreateInstance(NS_TIMER_CONTRACTID);
+    mDeleteTimer = NS_NewTimer();
     NS_ENSURE_STATE(mDeleteTimer);
 
     if (QuotaManager* quotaManager = QuotaManager::Get()) {
       NoteLiveQuotaManager(quotaManager);
     }
   }
 
   Preferences::RegisterCallbackAndCall(AtomicBoolPrefChangedCallback,
--- a/dom/ipc/ContentChild.cpp
+++ b/dom/ipc/ContentChild.cpp
@@ -2945,24 +2945,23 @@ void
 ContentChild::StartForceKillTimer()
 {
   if (mForceKillTimer) {
     return;
   }
 
   int32_t timeoutSecs = Preferences::GetInt("dom.ipc.tabs.shutdownTimeoutSecs", 5);
   if (timeoutSecs > 0) {
-    mForceKillTimer = do_CreateInstance("@mozilla.org/timer;1");
+    NS_NewTimerWithFuncCallback(getter_AddRefs(mForceKillTimer),
+                                ContentChild::ForceKillTimerCallback,
+                                this,
+                                timeoutSecs * 1000,
+                                nsITimer::TYPE_ONE_SHOT,
+                                "dom::ContentChild::StartForceKillTimer");
     MOZ_ASSERT(mForceKillTimer);
-    mForceKillTimer->InitWithNamedFuncCallback(
-      ContentChild::ForceKillTimerCallback,
-      this,
-      timeoutSecs * 1000,
-      nsITimer::TYPE_ONE_SHOT,
-      "dom::ContentChild::StartForceKillTimer");
   }
 }
 
 /* static */ void
 ContentChild::ForceKillTimerCallback(nsITimer* aTimer, void* aClosure)
 {
   ProcessChild::QuickExit();
 }
--- a/dom/ipc/ContentParent.cpp
+++ b/dom/ipc/ContentParent.cpp
@@ -1901,24 +1901,23 @@ void
 ContentParent::StartForceKillTimer()
 {
   if (mForceKillTimer || !mIPCOpen) {
     return;
   }
 
   int32_t timeoutSecs = Preferences::GetInt("dom.ipc.tabs.shutdownTimeoutSecs", 5);
   if (timeoutSecs > 0) {
-    mForceKillTimer = do_CreateInstance("@mozilla.org/timer;1");
+    NS_NewTimerWithFuncCallback(getter_AddRefs(mForceKillTimer),
+                                ContentParent::ForceKillTimerCallback,
+                                this,
+                                timeoutSecs * 1000,
+                                nsITimer::TYPE_ONE_SHOT,
+                                "dom::ContentParent::StartForceKillTimer");
     MOZ_ASSERT(mForceKillTimer);
-    mForceKillTimer->InitWithNamedFuncCallback(
-      ContentParent::ForceKillTimerCallback,
-      this,
-      timeoutSecs * 1000,
-      nsITimer::TYPE_ONE_SHOT,
-      "dom::ContentParent::StartForceKillTimer");
   }
 }
 
 void
 ContentParent::NotifyTabDestroyed(const TabId& aTabId,
                                   bool aNotifiedDestroying)
 {
   if (aNotifiedDestroying) {
--- a/dom/ipc/ProcessPriorityManager.cpp
+++ b/dom/ipc/ProcessPriorityManager.cpp
@@ -808,18 +808,18 @@ ParticularProcessPriorityManager::Schedu
       timeout = sBackgroundGracePeriodMS;
       break;
     default:
       MOZ_ASSERT(false, "Unrecognized timeout pref");
       break;
   }
 
   LOGP("Scheduling reset timer to fire in %dms.", timeout);
-  mResetPriorityTimer = do_CreateInstance(NS_TIMER_CONTRACTID);
-  mResetPriorityTimer->InitWithCallback(this, timeout, nsITimer::TYPE_ONE_SHOT);
+  NS_NewTimerWithCallback(getter_AddRefs(mResetPriorityTimer),
+                          this, timeout, nsITimer::TYPE_ONE_SHOT);
 }
 
 NS_IMETHODIMP
 ParticularProcessPriorityManager::Notify(nsITimer* aTimer)
 {
   LOGP("Reset priority timer callback; about to ResetPriorityNow.");
   ResetPriorityNow();
   mResetPriorityTimer = nullptr;
--- a/dom/media/CanvasCaptureMediaStream.cpp
+++ b/dom/media/CanvasCaptureMediaStream.cpp
@@ -135,25 +135,22 @@ public:
     : OutputStreamDriver(aSourceStream, aTrackId, aPrincipalHandle)
     , mFPS(aFPS)
     , mTimer(nullptr)
   {
     if (mFPS == 0.0) {
       return;
     }
 
-    mTimer = do_CreateInstance(NS_TIMER_CONTRACTID);
-    if (!mTimer) {
-      return;
-    }
-    mTimer->InitWithNamedFuncCallback(&TimerTick,
-                                      this,
-                                      int(1000 / mFPS),
-                                      nsITimer::TYPE_REPEATING_SLACK,
-                                      "dom::TimerDriver::TimerDriver");
+    NS_NewTimerWithFuncCallback(getter_AddRefs(mTimer),
+                                &TimerTick,
+                                this,
+                                int(1000 / mFPS),
+                                nsITimer::TYPE_REPEATING_SLACK,
+                                "dom::TimerDriver::TimerDriver");
   }
 
   static void TimerTick(nsITimer* aTimer, void* aClosure)
   {
     MOZ_ASSERT(aClosure);
     TimerDriver* driver = static_cast<TimerDriver*>(aClosure);
 
     driver->RequestFrameCapture();
--- a/dom/media/ChannelMediaDecoder.cpp
+++ b/dom/media/ChannelMediaDecoder.cpp
@@ -25,18 +25,17 @@ ChannelMediaDecoder::ResourceCallback::R
   MOZ_ASSERT(aMainThread);
 }
 
 void
 ChannelMediaDecoder::ResourceCallback::Connect(ChannelMediaDecoder* aDecoder)
 {
   MOZ_ASSERT(NS_IsMainThread());
   mDecoder = aDecoder;
-  mTimer = do_CreateInstance("@mozilla.org/timer;1");
-  mTimer->SetTarget(mAbstractMainThread->AsEventTarget());
+  mTimer = NS_NewTimer(mAbstractMainThread->AsEventTarget());
 }
 
 void
 ChannelMediaDecoder::ResourceCallback::Disconnect()
 {
   MOZ_ASSERT(NS_IsMainThread());
   if (mDecoder) {
     mDecoder = nullptr;
--- a/dom/media/MediaDevices.cpp
+++ b/dom/media/MediaDevices.cpp
@@ -229,17 +229,17 @@ MediaDevices::OnDeviceChange()
 
   if (!(MediaManager::Get()->IsActivelyCapturingOrHasAPermission(GetOwner()->WindowID()) ||
     Preferences::GetBool("media.navigator.permission.disabled", false))) {
     return;
   }
 
   if (!mFuzzTimer)
   {
-    mFuzzTimer = do_CreateInstance(NS_TIMER_CONTRACTID);
+    mFuzzTimer = NS_NewTimer();
   }
 
   if (!mFuzzTimer) {
     MOZ_ASSERT(false);
     return;
   }
 
   mFuzzTimer->Cancel();
--- a/dom/media/MediaStreamGraph.cpp
+++ b/dom/media/MediaStreamGraph.cpp
@@ -1497,23 +1497,20 @@ MediaStreamGraphImpl::ForceShutDown(medi
   LOG(LogLevel::Debug, ("MediaStreamGraph %p ForceShutdown", this));
 
   MonitorAutoLock lock(mMonitor);
   if (aShutdownTicket) {
     MOZ_ASSERT(!mForceShutdownTicket);
     // Avoid waiting forever for a graph to shut down
     // synchronously.  Reports are that some 3rd-party audio drivers
     // occasionally hang in shutdown (both for us and Chrome).
-    mShutdownTimer = do_CreateInstance(NS_TIMER_CONTRACTID);
-    if (!mShutdownTimer) {
-      return;
-    }
-    mShutdownTimer->InitWithCallback(this,
-                                     MediaStreamGraph::AUDIO_CALLBACK_DRIVER_SHUTDOWN_TIMEOUT,
-                                     nsITimer::TYPE_ONE_SHOT);
+    NS_NewTimerWithCallback(getter_AddRefs(mShutdownTimer),
+                            this,
+                            MediaStreamGraph::AUDIO_CALLBACK_DRIVER_SHUTDOWN_TIMEOUT,
+                            nsITimer::TYPE_ONE_SHOT);
   }
   mForceShutDown = true;
   mForceShutdownTicket = aShutdownTicket;
   if (mLifecycleState == LIFECYCLE_THREAD_NOT_STARTED) {
     // We *could* have just sent this a message to start up, so don't
     // yank the rug out from under it.  Tell it to startup and let it
     // shut down.
     RefPtr<GraphDriver> driver = CurrentDriver();
--- a/dom/media/MediaTimer.cpp
+++ b/dom/media/MediaTimer.cpp
@@ -15,17 +15,17 @@
 
 namespace mozilla {
 
 NS_IMPL_ADDREF(MediaTimer)
 NS_IMPL_RELEASE_WITH_DESTROY(MediaTimer, DispatchDestroy())
 
 MediaTimer::MediaTimer()
   : mMonitor("MediaTimer Monitor")
-  , mTimer(do_CreateInstance("@mozilla.org/timer;1"))
+  , mTimer(NS_NewTimer())
   , mCreationTimeStamp(TimeStamp::Now())
   , mUpdateScheduled(false)
 {
   TIMER_LOG("MediaTimer::MediaTimer");
 
   // Use the SharedThreadPool to create an nsIThreadPool with a maximum of one
   // thread, which is equivalent to an nsIThread for our purposes.
   RefPtr<SharedThreadPool> threadPool(
--- a/dom/media/VideoUtils.cpp
+++ b/dom/media/VideoUtils.cpp
@@ -362,33 +362,23 @@ SimpleTimer::Init(nsIRunnable* aTask, ui
     target = aTarget;
   } else {
     target = GetMainThreadEventTarget();
     if (!target) {
       return NS_ERROR_NOT_AVAILABLE;
     }
   }
 
-  nsCOMPtr<nsITimer> timer = do_CreateInstance(NS_TIMER_CONTRACTID, &rv);
-  if (NS_FAILED(rv)) {
-    return rv;
-  }
-  // Note: set target before InitWithCallback in case the timer fires before
-  // we change the event target.
-  rv = timer->SetTarget(target);
-  if (NS_FAILED(rv)) {
-    timer->Cancel();
-    return rv;
-  }
-  rv = timer->InitWithCallback(this, aTimeoutMs, nsITimer::TYPE_ONE_SHOT);
+  rv = NS_NewTimerWithCallback(getter_AddRefs(mTimer),
+                               this, aTimeoutMs, nsITimer::TYPE_ONE_SHOT,
+                               target);
   if (NS_FAILED(rv)) {
     return rv;
   }
 
-  mTimer = timer.forget();
   mTask = aTask;
   return NS_OK;
 }
 
 NS_IMPL_ISUPPORTS(SimpleTimer, nsITimerCallback, nsINamed)
 
 already_AddRefed<SimpleTimer>
 SimpleTimer::Create(nsIRunnable* aTask, uint32_t aTimeoutMs, nsIEventTarget* aTarget)
--- a/dom/media/doctor/DecoderDoctorDiagnostics.cpp
+++ b/dom/media/doctor/DecoderDoctorDiagnostics.cpp
@@ -222,25 +222,18 @@ DecoderDoctorDocumentWatcher::StopWatchi
 }
 
 void
 DecoderDoctorDocumentWatcher::EnsureTimerIsStarted()
 {
   MOZ_ASSERT(NS_IsMainThread());
 
   if (!mTimer) {
-    mTimer = do_CreateInstance(NS_TIMER_CONTRACTID);
-    if (NS_WARN_IF(!mTimer)) {
-      return;
-    }
-    if (NS_WARN_IF(NS_FAILED(
-          mTimer->InitWithCallback(
-            this, sAnalysisPeriod_ms, nsITimer::TYPE_ONE_SHOT)))) {
-      mTimer = nullptr;
-    }
+    NS_NewTimerWithCallback(getter_AddRefs(mTimer),
+                            this, sAnalysisPeriod_ms, nsITimer::TYPE_ONE_SHOT);
   }
 }
 
 enum class ReportParam : uint8_t
 {
   // Marks the end of the parameter list.
   // Keep this zero! (For implicit zero-inits when used in definitions below.)
   None = 0,
--- a/dom/media/eme/MediaKeySystemAccessManager.cpp
+++ b/dom/media/eme/MediaKeySystemAccessManager.cpp
@@ -276,18 +276,20 @@ MediaKeySystemAccessManager::AwaitInstal
 {
   EME_LOG("MediaKeySystemAccessManager::AwaitInstall %s", NS_ConvertUTF16toUTF8(aKeySystem).get());
 
   if (!EnsureObserversAdded()) {
     NS_WARNING("Failed to add pref observer");
     return false;
   }
 
-  nsCOMPtr<nsITimer> timer(do_CreateInstance("@mozilla.org/timer;1"));
-  if (!timer || NS_FAILED(timer->Init(this, 60 * 1000, nsITimer::TYPE_ONE_SHOT))) {
+  nsCOMPtr<nsITimer> timer;
+  NS_NewTimerWithObserver(getter_AddRefs(timer),
+                          this, 60 * 1000, nsITimer::TYPE_ONE_SHOT);
+  if (!timer) {
     NS_WARNING("Failed to create timer to await CDM install.");
     return false;
   }
 
   mRequests.AppendElement(PendingRequest(aPromise, aKeySystem, aConfigs, timer));
   return true;
 }
 
--- a/dom/media/gmp/GMPTimerParent.cpp
+++ b/dom/media/gmp/GMPTimerParent.cpp
@@ -41,32 +41,29 @@ GMPTimerParent::RecvSetTimer(const uint3
   MOZ_ASSERT(mGMPEventTarget->IsOnCurrentThread());
 
   if (!mIsOpen) {
     return IPC_OK();
   }
 
   nsresult rv;
   nsAutoPtr<Context> ctx(new Context());
-  ctx->mTimer = do_CreateInstance("@mozilla.org/timer;1", &rv);
+
+  rv = NS_NewTimerWithFuncCallback(getter_AddRefs(ctx->mTimer),
+                                   &GMPTimerParent::GMPTimerExpired,
+                                   ctx,
+                                   aTimeoutMs,
+                                   nsITimer::TYPE_ONE_SHOT,
+                                   "gmp::GMPTimerParent::RecvSetTimer",
+                                   mGMPEventTarget);
   NS_ENSURE_SUCCESS(rv, IPC_OK());
 
   ctx->mId = aTimerId;
-  rv = ctx->mTimer->SetTarget(mGMPEventTarget);
-  NS_ENSURE_SUCCESS(rv, IPC_OK());
   ctx->mParent = this;
 
-  rv =
-    ctx->mTimer->InitWithNamedFuncCallback(&GMPTimerParent::GMPTimerExpired,
-                                           ctx,
-                                           aTimeoutMs,
-                                           nsITimer::TYPE_ONE_SHOT,
-                                           "gmp::GMPTimerParent::RecvSetTimer");
-  NS_ENSURE_SUCCESS(rv, IPC_OK());
-
   mTimers.PutEntry(ctx.forget());
 
   return IPC_OK();
 }
 
 void
 GMPTimerParent::Shutdown()
 {
--- a/dom/media/webrtc/MediaEngineDefault.cpp
+++ b/dom/media/webrtc/MediaEngineDefault.cpp
@@ -173,17 +173,17 @@ static void ReleaseFrame(layers::PlanarY
 nsresult
 MediaEngineDefaultVideoSource::Start(SourceMediaStream* aStream, TrackID aID,
                                      const PrincipalHandle& aPrincipalHandle)
 {
   if (mState != kAllocated) {
     return NS_ERROR_FAILURE;
   }
 
-  mTimer = do_CreateInstance(NS_TIMER_CONTRACTID);
+  mTimer = NS_NewTimer();
   if (!mTimer) {
     return NS_ERROR_FAILURE;
   }
 
   aStream->AddTrack(aID, 0, new VideoSegment(), SourceMediaStream::ADDTRACK_QUEUED);
 
   // Remember TrackID so we can end it later
   mTrackID = aID;
--- a/dom/media/webrtc/MediaEngineTabVideoSource.cpp
+++ b/dom/media/webrtc/MediaEngineTabVideoSource.cpp
@@ -46,18 +46,19 @@ MediaEngineTabVideoSource::MediaEngineTa
   , mDataSize(0)
   , mBlackedoutWindow(false)
   , mMonitor("MediaEngineTabVideoSource") {}
 
 nsresult
 MediaEngineTabVideoSource::StartRunnable::Run()
 {
   mVideoSource->Draw();
-  mVideoSource->mTimer = do_CreateInstance(NS_TIMER_CONTRACTID);
-  mVideoSource->mTimer->InitWithCallback(mVideoSource, mVideoSource->mTimePerFrame, nsITimer:: TYPE_REPEATING_SLACK);
+  NS_NewTimerWithCallback(getter_AddRefs(mVideoSource->mTimer),
+                          mVideoSource, mVideoSource->mTimePerFrame,
+                          nsITimer::TYPE_REPEATING_SLACK);
   if (mVideoSource->mTabSource) {
     mVideoSource->mTabSource->NotifyStreamStart(mVideoSource->mWindow);
   }
   return NS_OK;
 }
 
 nsresult
 MediaEngineTabVideoSource::StopRunnable::Run()
--- a/dom/media/webspeech/recognition/SpeechRecognition.cpp
+++ b/dom/media/webspeech/recognition/SpeechRecognition.cpp
@@ -112,17 +112,17 @@ NS_INTERFACE_MAP_END_INHERITING(DOMEvent
 
 NS_IMPL_ADDREF_INHERITED(SpeechRecognition, DOMEventTargetHelper)
 NS_IMPL_RELEASE_INHERITED(SpeechRecognition, DOMEventTargetHelper)
 
 SpeechRecognition::SpeechRecognition(nsPIDOMWindowInner* aOwnerWindow)
   : DOMEventTargetHelper(aOwnerWindow)
   , mEndpointer(kSAMPLE_RATE)
   , mAudioSamplesPerChunk(mEndpointer.FrameSize())
-  , mSpeechDetectionTimer(do_CreateInstance(NS_TIMER_CONTRACTID))
+  , mSpeechDetectionTimer(NS_NewTimer())
   , mSpeechGrammarList(new SpeechGrammarList(GetParentObject()))
   , mInterimResults(false)
   , mMaxAlternatives(1)
 {
   SR_LOG("created SpeechRecognition");
 
   if (MediaPrefs::WebSpeechTestEnabled()) {
     nsCOMPtr<nsIObserverService> obs = services::GetObserverService();
--- a/dom/plugins/base/nsNPAPIPluginInstance.cpp
+++ b/dom/plugins/base/nsNPAPIPluginInstance.cpp
@@ -1026,28 +1026,27 @@ nsNPAPIPluginInstance::ScheduleTimer(uin
   // generate ID that is unique to this instance
   uint32_t uniqueID = mTimers.Length();
   while ((uniqueID == 0) || TimerWithID(uniqueID, nullptr))
     uniqueID++;
   newTimer->id = uniqueID;
 
   // create new xpcom timer, scheduled correctly
   nsresult rv;
-  nsCOMPtr<nsITimer> xpcomTimer = do_CreateInstance(NS_TIMER_CONTRACTID, &rv);
+  const short timerType = (repeat ? (short)nsITimer::TYPE_REPEATING_SLACK : (short)nsITimer::TYPE_ONE_SHOT);
+  rv = NS_NewTimerWithFuncCallback(getter_AddRefs(newTimer->timer),
+                                   PluginTimerCallback,
+                                   newTimer,
+                                   interval,
+                                   timerType,
+                                   "nsNPAPIPluginInstance::ScheduleTimer");
   if (NS_FAILED(rv)) {
     delete newTimer;
     return 0;
   }
-  const short timerType = (repeat ? (short)nsITimer::TYPE_REPEATING_SLACK : (short)nsITimer::TYPE_ONE_SHOT);
-  xpcomTimer->InitWithNamedFuncCallback(PluginTimerCallback,
-                                        newTimer,
-                                        interval,
-                                        timerType,
-                                        "nsNPAPIPluginInstance::ScheduleTimer");
-  newTimer->timer = xpcomTimer;
 
   // save callback function
   newTimer->callback = timerFunc;
 
   // add timer to timers array
   mTimers.AppendElement(newTimer);
 
   return newTimer->id;
--- a/dom/plugins/base/nsNPAPIPluginStreamListener.cpp
+++ b/dom/plugins/base/nsNPAPIPluginStreamListener.cpp
@@ -267,24 +267,20 @@ nsNPAPIPluginStreamListener::ResumeReque
     mStreamListenerPeer->ResumeRequests();
   }
   mIsSuspended = false;
 }
 
 nsresult
 nsNPAPIPluginStreamListener::StartDataPump()
 {
-  nsresult rv;
-  mDataPumpTimer = do_CreateInstance("@mozilla.org/timer;1", &rv);
-  NS_ENSURE_SUCCESS(rv, rv);
-
   // Start pumping data to the plugin every 100ms until it obeys and
   // eats the data.
-  return mDataPumpTimer->InitWithCallback(this, 100,
-                                          nsITimer::TYPE_REPEATING_SLACK);
+  return NS_NewTimerWithCallback(getter_AddRefs(mDataPumpTimer),
+                                 this, 100, nsITimer::TYPE_REPEATING_SLACK);
 }
 
 void
 nsNPAPIPluginStreamListener::StopDataPump()
 {
   if (mDataPumpTimer) {
     mDataPumpTimer->Cancel();
     mDataPumpTimer = nullptr;
--- a/dom/plugins/base/nsPluginHost.cpp
+++ b/dom/plugins/base/nsPluginHost.cpp
@@ -652,17 +652,17 @@ void nsPluginHost::OnPluginInstanceDestr
   // retention and avoid perf hits for loading popular plugins.
   if (!hasInstance) {
     if (UnloadPluginsASAP()) {
       aPluginTag->TryUnloadPlugin(false);
     } else {
       if (aPluginTag->mUnloadTimer) {
         aPluginTag->mUnloadTimer->Cancel();
       } else {
-        aPluginTag->mUnloadTimer = do_CreateInstance(NS_TIMER_CONTRACTID);
+        aPluginTag->mUnloadTimer = NS_NewTimer();
       }
       uint32_t unloadTimeout = Preferences::GetUint(kPrefUnloadPluginTimeoutSecs,
                                                     kDefaultPluginUnloadingTimeout);
       aPluginTag->mUnloadTimer->InitWithCallback(this,
                                                  1000 * unloadTimeout,
                                                  nsITimer::TYPE_ONE_SHOT);
     }
   }
--- a/dom/plugins/base/nsPluginInstanceOwner.cpp
+++ b/dom/plugins/base/nsPluginInstanceOwner.cpp
@@ -1283,17 +1283,17 @@ bool nsPluginInstanceOwner::IsRemoteDraw
 
 NPEventModel nsPluginInstanceOwner::GetEventModel()
 {
   return mEventModel;
 }
 
 #define DEFAULT_REFRESH_RATE 20 // 50 FPS
 
-nsCOMPtr<nsITimer>               *nsPluginInstanceOwner::sCATimer = nullptr;
+StaticRefPtr<nsITimer>            nsPluginInstanceOwner::sCATimer;
 nsTArray<nsPluginInstanceOwner*> *nsPluginInstanceOwner::sCARefreshListeners = nullptr;
 
 void nsPluginInstanceOwner::CARefresh(nsITimer *aTimer, void *aClosure) {
   if (!sCARefreshListeners) {
     return;
   }
   for (size_t i = 0; i < sCARefreshListeners->Length(); i++) {
     nsPluginInstanceOwner* instanceOwner = (*sCARefreshListeners)[i];
@@ -1329,39 +1329,34 @@ void nsPluginInstanceOwner::AddToCARefre
   }
 
   if (sCARefreshListeners->Contains(this)) {
     return;
   }
 
   sCARefreshListeners->AppendElement(this);
 
-  if (!sCATimer) {
-    sCATimer = new nsCOMPtr<nsITimer>();
-  }
-
   if (sCARefreshListeners->Length() == 1) {
-    *sCATimer = do_CreateInstance("@mozilla.org/timer;1");
-    (*sCATimer)->InitWithNamedFuncCallback(CARefresh, nullptr,
-                                           DEFAULT_REFRESH_RATE, nsITimer::TYPE_REPEATING_SLACK,
-                                           "nsPluginInstanceOwner::CARefresh");
+    NS_NewTimerWithFuncCallback(getter_AddRefs(sCATimer),
+                                CARefresh, nullptr,
+                                DEFAULT_REFRESH_RATE, nsITimer::TYPE_REPEATING_SLACK,
+                                "nsPluginInstanceOwner::CARefresh");
   }
 }
 
 void nsPluginInstanceOwner::RemoveFromCARefreshTimer() {
   if (!sCARefreshListeners || sCARefreshListeners->Contains(this) == false) {
     return;
   }
 
   sCARefreshListeners->RemoveElement(this);
 
   if (sCARefreshListeners->Length() == 0) {
     if (sCATimer) {
-      (*sCATimer)->Cancel();
-      delete sCATimer;
+      sCATimer->Cancel();
       sCATimer = nullptr;
     }
     delete sCARefreshListeners;
     sCARefreshListeners = nullptr;
   }
 }
 
 void nsPluginInstanceOwner::SetPluginPort()
--- a/dom/presentation/PresentationSessionInfo.cpp
+++ b/dom/presentation/PresentationSessionInfo.cpp
@@ -1167,21 +1167,18 @@ PresentationPresentingInfo::Init(nsIPres
 {
   PresentationSessionInfo::Init(aControlChannel);
 
   // Add a timer to prevent waiting indefinitely in case the receiver page fails
   // to become ready.
   nsresult rv;
   int32_t timeout =
     Preferences::GetInt("presentation.receiver.loading.timeout", 10000);
-  mTimer = do_CreateInstance(NS_TIMER_CONTRACTID, &rv);
-  if (NS_WARN_IF(NS_FAILED(rv))) {
-    return rv;
-  }
-  rv = mTimer->InitWithCallback(this, timeout, nsITimer::TYPE_ONE_SHOT);
+  rv = NS_NewTimerWithCallback(getter_AddRefs(mTimer),
+                               this, timeout, nsITimer::TYPE_ONE_SHOT);
   if (NS_WARN_IF(NS_FAILED(rv))) {
     return rv;
   }
 
   return NS_OK;
 }
 
 void
--- a/dom/presentation/provider/MulticastDNSDeviceProvider.cpp
+++ b/dom/presentation/provider/MulticastDNSDeviceProvider.cpp
@@ -139,24 +139,24 @@ MulticastDNSDeviceProvider::Init()
     return rv;
   }
 
   mPresentationService = do_CreateInstance(PRESENTATION_CONTROL_SERVICE_CONTACT_ID, &rv);
   if (NS_WARN_IF(NS_FAILED(rv))) {
     return rv;
   }
 
-  mDiscoveryTimer = do_CreateInstance(NS_TIMER_CONTRACTID, &rv);
-  if (NS_WARN_IF(NS_FAILED(rv))) {
-    return rv;
+  mDiscoveryTimer = NS_NewTimer();
+  if (NS_WARN_IF(!mDiscoveryTimer)) {
+    return NS_ERROR_OUT_OF_MEMORY;
   }
 
-  mServerRetryTimer = do_CreateInstance(NS_TIMER_CONTRACTID, &rv);
-  if (NS_WARN_IF(NS_FAILED(rv))) {
-    return rv;
+  mServerRetryTimer = NS_NewTimer();
+  if (NS_WARN_IF(!mServerRetryTimer)) {
+    return NS_ERROR_OUT_OF_MEMORY;
   }
   Preferences::AddStrongObservers(this, kObservedPrefs);
 
   mDiscoveryEnabled = Preferences::GetBool(PREF_PRESENTATION_DISCOVERY);
   mDiscoveryTimeoutMs = Preferences::GetUint(PREF_PRESENTATION_DISCOVERY_TIMEOUT_MS);
   mDiscoverable = Preferences::GetBool(PREF_PRESENTATION_DISCOVERABLE);
   mDiscoverableEncrypted = Preferences::GetBool(PREF_PRESENTATION_DISCOVERABLE_ENCRYPTED);
   mServerRetryMs = Preferences::GetUint(PREF_PRESENTATION_DISCOVERABLE_RETRY_MS);
--- a/dom/quota/ActorsParent.cpp
+++ b/dom/quota/ActorsParent.cpp
@@ -3614,17 +3614,17 @@ QuotaManager::Init(const nsAString& aBas
 
   rv = NS_NewNamedThread("QuotaManager IO", getter_AddRefs(mIOThread));
   if (NS_WARN_IF(NS_FAILED(rv))) {
     return rv;
   }
 
   // Make a timer here to avoid potential failures later. We don't actually
   // initialize the timer until shutdown.
-  mShutdownTimer = do_CreateInstance(NS_TIMER_CONTRACTID);
+  mShutdownTimer = NS_NewTimer();
   if (NS_WARN_IF(!mShutdownTimer)) {
     return NS_ERROR_FAILURE;
   }
 
   static_assert(Client::IDB == 0 && Client::ASMJS == 1 && Client::DOMCACHE == 2 &&
                 Client::TYPE_MAX == 3, "Fix the registration!");
 
   MOZ_ASSERT(mClients.Capacity() == Client::TYPE_MAX,
--- a/dom/storage/StorageObserver.cpp
+++ b/dom/storage/StorageObserver.cpp
@@ -206,24 +206,18 @@ StorageObserver::Observe(nsISupports* aS
 
   // Start the thread that opens the database.
   if (!strcmp(aTopic, kStartupTopic)) {
     MOZ_ASSERT(XRE_IsParentProcess());
 
     nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
     obs->RemoveObserver(this, kStartupTopic);
 
-    mDBThreadStartDelayTimer = do_CreateInstance(NS_TIMER_CONTRACTID);
-    if (!mDBThreadStartDelayTimer) {
-      return NS_ERROR_UNEXPECTED;
-    }
-
-    mDBThreadStartDelayTimer->Init(this, nsITimer::TYPE_ONE_SHOT, kStartupDelay);
-
-    return NS_OK;
+    return NS_NewTimerWithObserver(getter_AddRefs(mDBThreadStartDelayTimer),
+                                   this, nsITimer::TYPE_ONE_SHOT, kStartupDelay);
   }
 
   // Timer callback used to start the database a short timer after startup
   if (!strcmp(aTopic, NS_TIMER_CALLBACK_TOPIC)) {
     MOZ_ASSERT(XRE_IsParentProcess());
 
     nsCOMPtr<nsITimer> timer = do_QueryInterface(aSubject);
     if (!timer) {
--- a/dom/workers/RuntimeService.cpp
+++ b/dom/workers/RuntimeService.cpp
@@ -1979,17 +1979,17 @@ RuntimeService::Init()
 
   // nsIStreamTransportService is thread-safe but it must be initialized on the
   // main-thread. FileReader needs it, so, let's initialize it now.
   nsresult rv;
   nsCOMPtr<nsIStreamTransportService> sts =
     do_GetService(kStreamTransportServiceCID, &rv);
   NS_ENSURE_TRUE(sts, NS_ERROR_FAILURE);
 
-  mIdleThreadTimer = do_CreateInstance(NS_TIMER_CONTRACTID);
+  mIdleThreadTimer = NS_NewTimer();
   NS_ENSURE_STATE(mIdleThreadTimer);
 
   nsCOMPtr<nsIObserverService> obs = services::GetObserverService();
   NS_ENSURE_TRUE(obs, NS_ERROR_FAILURE);
 
   rv = obs->AddObserver(this, NS_XPCOM_SHUTDOWN_THREADS_OBSERVER_ID, false);
   NS_ENSURE_SUCCESS(rv, rv);
 
--- a/dom/workers/ServiceWorkerManager.cpp
+++ b/dom/workers/ServiceWorkerManager.cpp
@@ -4335,33 +4335,28 @@ ServiceWorkerManager::ScheduleUpdateTime
   if (timer) {
     // There is already a timer scheduled.  In this case just use the original
     // schedule time.  We don't want to push it out to a later time since that
     // could allow updates to be starved forever if events are continuously
     // fired.
     return;
   }
 
-  timer = do_CreateInstance("@mozilla.org/timer;1", &rv);
-  if (NS_WARN_IF(NS_FAILED(rv))) {
-    data->mUpdateTimers.Remove(aScope); // another lookup, but very rare
-    return;
-  }
-
-  // Label with SystemGroup because UpdateTimerCallback only sends an IPC message
-  // (PServiceWorkerUpdaterConstructor) without touching any web contents.
-  timer->SetTarget(SystemGroup::EventTargetFor(TaskCategory::Other));
-
   nsCOMPtr<nsITimerCallback> callback = new UpdateTimerCallback(aPrincipal,
                                                                 aScope);
 
   const uint32_t UPDATE_DELAY_MS = 1000;
 
-  rv = timer->InitWithCallback(callback, UPDATE_DELAY_MS,
-                               nsITimer::TYPE_ONE_SHOT);
+  // Label with SystemGroup because UpdateTimerCallback only sends an IPC message
+  // (PServiceWorkerUpdaterConstructor) without touching any web contents.
+  rv = NS_NewTimerWithCallback(getter_AddRefs(timer),
+                               callback, UPDATE_DELAY_MS,
+                               nsITimer::TYPE_ONE_SHOT,
+                               SystemGroup::EventTargetFor(TaskCategory::Other));
+
   if (NS_WARN_IF(NS_FAILED(rv))) {
     data->mUpdateTimers.Remove(aScope); // another lookup, but very rare
     return;
   }
 }
 
 void
 ServiceWorkerManager::UpdateTimerFired(nsIPrincipal* aPrincipal,
--- a/dom/workers/ServiceWorkerPrivate.cpp
+++ b/dom/workers/ServiceWorkerPrivate.cpp
@@ -84,17 +84,17 @@ NS_IMPL_ISUPPORTS0(KeepAliveToken)
 ServiceWorkerPrivate::ServiceWorkerPrivate(ServiceWorkerInfo* aInfo)
   : mInfo(aInfo)
   , mDebuggerCount(0)
   , mTokenCount(0)
 {
   AssertIsOnMainThread();
   MOZ_ASSERT(aInfo);
 
-  mIdleWorkerTimer = do_CreateInstance(NS_TIMER_CONTRACTID);
+  mIdleWorkerTimer = NS_NewTimer();
   MOZ_ASSERT(mIdleWorkerTimer);
 }
 
 ServiceWorkerPrivate::~ServiceWorkerPrivate()
 {
   MOZ_ASSERT(!mWorkerPrivate);
   MOZ_ASSERT(!mTokenCount);
   MOZ_ASSERT(!mInfo);
@@ -1095,23 +1095,18 @@ class AllowWindowInteractionHandler fina
   void
   StartClearWindowTimer(WorkerPrivate* aWorkerPrivate)
   {
     MOZ_ASSERT(aWorkerPrivate);
     aWorkerPrivate->AssertIsOnWorkerThread();
     MOZ_ASSERT(!mTimer);
 
     nsresult rv;
-    nsCOMPtr<nsITimer> timer = do_CreateInstance(NS_TIMER_CONTRACTID, &rv);
-    if (NS_WARN_IF(NS_FAILED(rv))) {
-      return;
-    }
-
-    rv = timer->SetTarget(aWorkerPrivate->ControlEventTarget());
-    if (NS_WARN_IF(NS_FAILED(rv))) {
+    nsCOMPtr<nsITimer> timer = NS_NewTimer(aWorkerPrivate->ControlEventTarget());
+    if (NS_WARN_IF(!timer)) {
       return;
     }
 
     if (!HoldWorker(aWorkerPrivate, Closing)) {
       return;
     }
 
     aWorkerPrivate->GlobalScope()->AllowWindowInteraction();
--- a/dom/workers/WorkerPrivate.cpp
+++ b/dom/workers/WorkerPrivate.cpp
@@ -5291,17 +5291,17 @@ WorkerPrivate::InitializeGCTimers()
 {
   AssertIsOnWorkerThread();
 
   // We need a timer for GC. The basic plan is to run a non-shrinking GC
   // periodically (PERIODIC_GC_TIMER_DELAY_SEC) while the worker is running.
   // Once the worker goes idle we set a short (IDLE_GC_TIMER_DELAY_SEC) timer to
   // run a shrinking GC. If the worker receives more messages then the short
   // timer is canceled and the periodic timer resumes.
-  mGCTimer = do_CreateInstance(NS_TIMER_CONTRACTID);
+  mGCTimer = NS_NewTimer();
   MOZ_ASSERT(mGCTimer);
 
   mPeriodicGCTimerRunning = false;
   mIdleGCTimerRunning = false;
 }
 
 void
 WorkerPrivate::SetGCTimerMode(GCTimerMode aMode)
@@ -6477,22 +6477,20 @@ WorkerPrivate::SetTimeout(JSContext* aCx
     mTimeouts.InsertElementSorted(newInfo.forget(), GetAutoPtrComparator(mTimeouts));
 
   LOG(TimeoutsLog(), ("Worker %p has new timeout: delay=%d interval=%s\n",
                       this, aTimeout, aIsInterval ? "yes" : "no"));
 
   // If the timeout we just made is set to fire next then we need to update the
   // timer, unless we're currently running timeouts.
   if (insertedInfo == mTimeouts.Elements() && !mRunningExpiredTimeouts) {
-    nsresult rv;
-
     if (!mTimer) {
-      mTimer = do_CreateInstance(NS_TIMER_CONTRACTID, &rv);
-      if (NS_FAILED(rv)) {
-        aRv.Throw(rv);
+      mTimer = NS_NewTimer();
+      if (!mTimer) {
+        aRv.Throw(NS_ERROR_UNEXPECTED);
         return 0;
       }
 
       mTimerRunnable = new TimerRunnable(this);
     }
 
     if (!mTimerRunning) {
       if (!ModifyBusyCountFromWorker(true)) {
--- a/dom/xbl/nsBindingManager.cpp
+++ b/dom/xbl/nsBindingManager.cpp
@@ -388,25 +388,23 @@ nsBindingManager::DoProcessAttachedQueue
   } else {
     // Someone's doing event processing from inside a constructor.
     // They're evil, but we'll fight back!  Just poll on them being
     // done and repost the attached queue event.
     //
     // But don't poll in a tight loop -- otherwise we keep the Gecko
     // event loop non-empty and trigger bug 1021240 on OS X.
     nsresult rv = NS_ERROR_FAILURE;
-    nsCOMPtr<nsITimer> timer = do_CreateInstance(NS_TIMER_CONTRACTID);
-    if (timer) {
-      rv = timer->InitWithNamedFuncCallback(
-        PostPAQEventCallback,
-        this,
-        100,
-        nsITimer::TYPE_ONE_SHOT,
-        "nsBindingManager::DoProcessAttachedQueue");
-    }
+    nsCOMPtr<nsITimer> timer;
+    rv = NS_NewTimerWithFuncCallback(getter_AddRefs(timer),
+                                     PostPAQEventCallback,
+                                     this,
+                                     100,
+                                     nsITimer::TYPE_ONE_SHOT,
+                                     "nsBindingManager::DoProcessAttachedQueue");
     if (NS_SUCCEEDED(rv)) {
       NS_ADDREF_THIS();
       // We drop our reference to the timer here, since the timer callback is
       // responsible for releasing the object.
       Unused << timer.forget().take();
     }
   }
 
--- a/dom/xhr/XMLHttpRequestMainThread.cpp
+++ b/dom/xhr/XMLHttpRequestMainThread.cpp
@@ -3285,17 +3285,17 @@ XMLHttpRequestMainThread::StartTimeoutTi
     mTimeoutTimer->Cancel();
   }
 
   if (!mTimeoutMilliseconds) {
     return;
   }
 
   if (!mTimeoutTimer) {
-    mTimeoutTimer = do_CreateInstance(NS_TIMER_CONTRACTID);
+    mTimeoutTimer = NS_NewTimer();
     SetTimerEventTarget(mTimeoutTimer);
   }
   uint32_t elapsed =
     (uint32_t)((PR_Now() - mRequestSentTime) / PR_USEC_PER_MSEC);
   mTimeoutTimer->InitWithCallback(
     this,
     mTimeoutMilliseconds > elapsed ? mTimeoutMilliseconds - elapsed : 0,
     nsITimer::TYPE_ONE_SHOT
@@ -3764,17 +3764,17 @@ XMLHttpRequestMainThread::StopProgressEv
     mProgressNotifier->Cancel();
   }
 }
 
 void
 XMLHttpRequestMainThread::StartProgressEventTimer()
 {
   if (!mProgressNotifier) {
-    mProgressNotifier = do_CreateInstance(NS_TIMER_CONTRACTID);
+    mProgressNotifier = NS_NewTimer();
     SetTimerEventTarget(mProgressNotifier);
   }
   if (mProgressNotifier) {
     mProgressTimerIsActive = true;
     mProgressNotifier->Cancel();
     mProgressNotifier->InitWithCallback(this, NS_PROGRESS_EVENT_INTERVAL,
                                         nsITimer::TYPE_ONE_SHOT);
   }
@@ -3791,17 +3791,17 @@ XMLHttpRequestMainThread::MaybeStartSync
   }
 
   // If we are in a beforeunload or a unload event, we must force a timeout.
   TimeDuration diff = (TimeStamp::NowLoRes() - doc->GetPageUnloadingEventTimeStamp());
   if (diff.ToMilliseconds() > MAX_SYNC_TIMEOUT_WHEN_UNLOADING) {
     return eErrorOrExpired;
   }
 
-  mSyncTimeoutTimer = do_CreateInstance(NS_TIMER_CONTRACTID);
+  mSyncTimeoutTimer = NS_NewTimer();
   SetTimerEventTarget(mSyncTimeoutTimer);
   if (!mSyncTimeoutTimer) {
     return eErrorOrExpired;
   }
 
   uint32_t timeout = MAX_SYNC_TIMEOUT_WHEN_UNLOADING - diff.ToMilliseconds();
   nsresult rv = mSyncTimeoutTimer->InitWithCallback(this, timeout,
                                                     nsITimer::TYPE_ONE_SHOT);