How to Use the onfade Callback in Howler.js

This article explains how to use the onfade callback in Howler.js to execute code immediately after an audio volume transition completes. You will learn how to define this callback during initialization, how to register it dynamically, and how to use it in common scenarios like pausing a sound after a fade-out.

Understanding the onfade Callback

In Howler.js, the fade() method transitions the volume of a sound from one level to another over a specified duration. The onfade callback is an event listener that triggers automatically once this volume transition finishes.

There are two primary ways to implement the onfade callback in your project.

Method 1: Defining onfade During Initialization

You can declare the onfade callback directly inside the Howler configuration object when you instantiate a new sound.

const sound = new Howl({
  src: ['track.mp3'],
  volume: 1.0,
  onfade: function(soundId) {
    console.log(`Fade transition completed for sound ID: ${soundId}`);
  }
});

// Trigger a fade from 1.0 (100%) to 0.0 (0%) over 2000 milliseconds
sound.play();
sound.fade(1.0, 0.0, 2000);

Method 2: Listening for the Fade Event Dynamically

If you only want to listen for a fade event at a specific moment, you can register the callback dynamically using the .once() or .on() methods. Using .once() is highly recommended for fades so the event listener automatically detaches itself after running.

const sound = new Howl({
  src: ['track.mp3']
});

sound.play();

// Trigger a fade-out over 3 seconds
sound.fade(1.0, 0.0, 3000);

// Listen for this specific fade to complete
sound.once('fade', function(soundId) {
  console.log('Fade-out complete. Pausing audio to save resources.');
  sound.pause(soundId);
});

Common Use Case: Fading Out and Pausing

A common mistake is forgetting to pause or stop audio after fading the volume to 0.0. If you do not pause the sound, it will continue to play silently in the background, consuming CPU resources.

The onfade callback solves this problem:

function fadeAndPause(soundInstance) {
  // Fade volume to 0 over 1.5 seconds
  soundInstance.fade(soundInstance.volume(), 0.0, 1500);

  // Pause the sound as soon as the fade finishes
  soundInstance.once('fade', function() {
    soundInstance.pause();
    // Reset volume back to default for the next play
    soundInstance.volume(1.0); 
  });
}