← Torna al blog

Dev Tips

Un trucchetto al giorno leva le complicazioni di torno! Piccole "scorciatoie" che possono facilitare la vita degli sviluppatori e far risparmiare tempo...e righe di codice.

95

Use signal to abort a Promise

2021-06-07

1// JS Tip of the Day
2// Use signal to abort a Promise
3
4const controller = new AbortController();
5const { signal } = controller;
6
7fetch("https://jsonplaceholder.typicode.com/todos/", { signal })
8  .then(res => {
9    console.log(res);
10  })
11  .catch(err => {
12    console.error(err);
13});
14
15// Abort request
16controller.abort(); // The user aborted a request.
94

Write an error message based on an assertion

2021-06-04

1// JS Tip of the Day
2// Write an error message based on an assertion 
3
4let isHero = false;
5console.assert(isHero, 'No, you aren\'t a hero!');
6// No, you aren't a hero!
7
8isHero = true;
9console.assert(isHero, 'No, you aren\'t a hero!'); // nothing to log
10
93

How to check if the document becomes visible or hidden

2021-06-03

1// JS Tip of the Day
2// How to check if the document becomes visible or hidden
3
4document.addEventListener("visibilitychange", function() {
5  console.log(document.visibilityState);
6  /* 
7  	You can stop or activate the UI updates or any tasks that the user doesn't want to
8    have running in the background. 
9  */
10})
92

How to check DOM mutations

2021-06-01

1// JS Tip of the Day
2// How to check DOM mutations
3
4// <p id="hero" class="old-hero">I'm Batman!</p>
5
6const callback = mutation => console.log(mutation);
7
8const observer = new MutationObserver(callback);
9const node = document.getElementById('hero');
10const config = {
11  attributes: true,
12  attributeFilter: ['class'],
13  attributeOldValue: true 
14};
15
16observer.observe(node, config);
17
18setTimeout(() => node.className = 'new-hero', 3000);
19/*
20[
21  {
22    ...
23	attributeName: "class",
24	...
25	oldValue: 'old-hero',
26	target: p#hero.new-hero { ... }
27	type: "attributes",
28	...
29  }
30]
31*/
91

How to detect online/offline status

2021-05-31

1// JS Tip of the Day
2// How to detect online/offline status
3
4window.addEventListener('online',  checkNetworkStatus);
5window.addEventListener('offline', checkNetworkStatus);
6
7function checkNetworkStatus(e) {
8  return navigator.onLine ? "online" : "offline";
9}

Contattaci.

Hai in mente un progetto e vorresti realizzarlo?
Sei interessato a migliorare le competenze del tuo team in ambito di programmazione e sviluppo?
Oppure vuoi semplicemente prendere prendere un caffè con noi e vedere la nostra collezione di Action Figure, allora scrivici tramite questo form.

Se, invece, vuoi far parte del team, guarda le nostre offerte di lavoro.

Questo sito è protetto da reCAPTCHA e si applicano le Norme sulla privacy e i Termini di servizio di Google.