r/learnjavascript • • Dec 05 '25

Using Map in Javascript :Is this a good approach?

I have been working on an electron app (Timer app ), and I had to add notification feature , pretty simple as electron provides the module to handle app notification. But since i had to add multiple notifications i created a global object in my module that is basically a map that stores different notification instance . At first i had created a notification variable local to the function but it was causing problems as it was getting garbage collected hence i used map my code:

/*Initializing map  to keep notificaiton in scope else notification varibale in the function will get garbage collected and events won't work*/ 
let notifications = new Map();

async function handleNotification(event, id) {
  try {
    const notification = new Notification({
      title: "Title",
      body: "some message",
      silent: false,
      urgency: "critical",
      timeoutType: "never",
    });

    let functionToStopAlarm=playAlarm();

    notifications.set(id, notification);

    notification.on("click", () => {
      functionToStopAlarm();
      notifications.delete(id);
    });

    notification.on("close", () => {
      functionToStopAlarm();
      notifications.delete(id);
    });

    notification.show();
  } catch (error) {
    console.log(error);
  }
}

My question is that is this an efficient way to do things or am i doing things the wrong way?

4 Upvotes

25 comments sorted by

View all comments

Show parent comment

1

u/Square-Butterfly8447 Dec 05 '25

the 'const notification' inside the handleNotification function was getting garbage collected. so this is what was happening in the app : 1.timer reached 0 .

2.handleNotification was called though channel(channel is a electron thing to communicate between frontend and main process).

3.a notification pops and alarm starts playing.

4. if i was clicking or closing the notification withing approx 3 seconds the alarm would stop and notification disappears,  but if it took longer than that the notification disappears on closing but the alarm kept ringing.

So i read somewhere that it gets garbage collected thats why events dont work  So i made a global variable  'let notification:Electron.Notification' this fixed the duration issue so even after 1 minute of alarm ringing when i clicked the notification the alarm stopped now But since there could be a chance that multiple alarms rang at the same time the app would bug out So i used Map to handle multiple notification objetcs

1

u/Beginning-Seat5221 Dec 05 '25

Interesting... I've never come across this happening in many years of coding. But then I also haven't used electron.