1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
9 // Netscape Communications
11 // See documentation in associated header file
14 #include "nsRepeatService.h"
15 #include "mozilla/StaticPtr.h"
16 #include "mozilla/dom/Document.h"
18 using namespace mozilla
;
20 static StaticAutoPtr
<nsRepeatService
> gRepeatService
;
22 nsRepeatService::nsRepeatService()
23 : mCallback(nullptr), mCallbackData(nullptr) {}
25 nsRepeatService::~nsRepeatService() {
26 NS_ASSERTION(!mCallback
&& !mCallbackData
,
27 "Callback was not removed before shutdown");
31 nsRepeatService
* nsRepeatService::GetInstance() {
32 if (!gRepeatService
) {
33 gRepeatService
= new nsRepeatService();
35 return gRepeatService
;
39 void nsRepeatService::Shutdown() { gRepeatService
= nullptr; }
41 void nsRepeatService::Start(Callback aCallback
, void* aCallbackData
,
42 dom::Document
* aDocument
,
43 const nsACString
& aCallbackName
,
44 uint32_t aInitialDelay
) {
45 MOZ_ASSERT(aCallback
!= nullptr, "null ptr");
47 mCallback
= aCallback
;
48 mCallbackData
= aCallbackData
;
49 mCallbackName
= aCallbackName
;
51 mRepeatTimer
= NS_NewTimer(GetMainThreadSerialEventTarget());
54 InitTimerCallback(aInitialDelay
);
58 void nsRepeatService::Stop(Callback aCallback
, void* aCallbackData
) {
59 if (mCallback
!= aCallback
|| mCallbackData
!= aCallbackData
) {
63 // printf("Stopping repeat timer\n");
65 mRepeatTimer
->Cancel();
66 mRepeatTimer
= nullptr;
69 mCallbackData
= nullptr;
72 void nsRepeatService::InitTimerCallback(uint32_t aInitialDelay
) {
77 mRepeatTimer
->InitWithNamedFuncCallback(
78 [](nsITimer
* aTimer
, void* aClosure
) {
79 // Use gRepeatService instead of nsRepeatService::GetInstance() (because
80 // we don't want nsRepeatService::GetInstance() to re-create a new
81 // instance for us, if we happen to get invoked after
82 // nsRepeatService::Shutdown() has nulled out gRepeatService).
83 nsRepeatService
* rs
= gRepeatService
;
89 rs
->mCallback(rs
->mCallbackData
);
92 rs
->InitTimerCallback(REPEAT_DELAY
);
94 nullptr, aInitialDelay
, nsITimer::TYPE_ONE_SHOT
, mCallbackName
.Data());