How to run tasks in background without using service workers in javascript

How to Run Background Tasks with JavaScript’s onvisibilitychange — And Why It's Cooler Than You Think! 🚀

So, you're staring at your website, pondering the great mysteries of life. "Is there a way," you ask yourself, "to run some background tasks in JavaScript when nobody's looking?"

Well, my friend, let me introduce you to the wonder that is onvisibilitychange — a hidden gem in JavaScript that can help you run sneaky little tasks when your users aren't paying attention. Whether you're updating data, pausing videos, or simply trolling your users by changing the page title to "HEY COME BACK," this trick has got you covered.

Let's dive in!

The Magic Behind document.visibilityState 🌟

First things first, you need to know about the Document Visibility API — basically, a fancy way for your website to say, "Hey, I'm here!" or "Nah, nobody's looking at me right now." It has two main states:

  • visible: When your website is the star of the show (front and center of the screen).
  • hidden: When your website is backstage, in the shadows, waiting to perform its next act (i.e., in a background tab).

Enter onvisibilitychange. This beautiful event is triggered whenever the visibility state changes — meaning whenever your user changes tabs, minimizes the browser, or does anything else to put your site in the background or bring it back to the front.

So, What Can You Do with This?

Glad you asked! Here's how you can set up a simple script to detect when your page goes from being visible to hidden and vice versa.

document.addEventListener("visibilitychange", function() {
  if (document.visibilityState === 'hidden') {
    console.log("Shhh... User's gone. Let's run our secret background task!");
    // Start your background task here
  } else {
    console.log("Aha! They're back! Better act normal...");
    // Stop or modify the task as needed
  }
});

A Real-World Example: Pretending to Be Productive 🕵️‍♂️

Imagine you're building a website that fetches data from an API every few seconds. But wait — do you really want to waste all that precious bandwidth when nobody's even looking at your tab? Nope, of course not! Instead, you can use onvisibilitychange to pause your fetch requests when the page isn't visible.

let fetchInterval;

document.addEventListener("visibilitychange", function() {
  if (document.visibilityState === 'visible') {
    console.log("User's watching! Let's fetch some data.");
    fetchInterval = setInterval(() => {
      // Your awesome fetch function here
      console.log("Fetching fresh data...");
    }, 5000); // Fetch every 5 seconds
  } else {
    console.log("User's gone! No need to fetch data.");
    clearInterval(fetchInterval);
  }
});

Cool Tricks and Hacks You Didn't Ask For 🤓

But wait, there's more! The onvisibilitychange event is like that Swiss Army knife you never knew you needed. Here are a few more things you can do:

Pause Videos or Animations: Automatically pause videos or animations when the user switches tabs. Nobody wants to miss the dramatic cliffhanger while they're checking memes on another tab!

Play with Page Titles: Want to get your users' attention? Change the page title when they leave the tab:

document.addEventListener("visibilitychange", function() {
  if (document.visibilityState === 'hidden') {
    document.title = "😢 Come Back, We Miss You!";
  } else {
    document.title = "Welcome Back, Hero!";
  }
});

Save Precious CPU and Battery: Running complex calculations or resource-heavy tasks? Pause them when the user isn’t watching. Your users’ devices will thank you!

Conclusion: Be a JavaScript Ninja! 🥷

Now you're armed with the power of onvisibilitychange, ready to build smarter, more efficient websites! You can manage background tasks like a pro, save on resources, and maybe even have a little fun along the way.

So, go ahead, give it a try! Make your users feel like you’re always watching (in a good way, of course)! And remember, with great power comes great... visibility change events.

Happy coding! 🎉