Screen Wake Lock Utility in Vanilla JavaScript

November 04, 2024

This utility schedules a screen wake lock job, introducing a slight delay for the wake state to change when multiple lock requests are made within a short timeframe.

screen-awake-util.js

requestQueue: [
  'lock',
  'release',
  'lock',
  'lock',
  'lock',
  'release' // This job may take some time to execute
],

The delay is subtle, but it's recommended to configure onStateChange to keep the user informed.

Interfaces

let SELF = {
    Toggle,
    Lock,
    Release,
    Configure,
};

Lock

// Prevents screen from sleeping
screenAwakeUtil.Lock();

Release

// Releases the wake lock
screenAwakeUtil.Release();

Toggle

let isReleased = screenAwakeUtil.Toggle();

if (isReleased) {
  console.log('Screen wake lock disabled.');
}

Configure

To display the state of the screen wake lock request, configure the onStateChange callback.

function listenWakeLockStateChange() {
  screenAwakeUtil.Configure({
    onStateChange: (state) => {
      switch (state) {
        case 0: // off
          $('._txtKeepAwake').replaceChildren('off');
          break;
        case 1: // on
          $('._txtKeepAwake').replaceChildren('on');
          break;
        case 2: // loading (queue)
          $('._txtKeepAwake').replaceChildren('loading');
          break;
        case 3: // failed
          $('._txtKeepAwake').replaceChildren('off (failed)');
          break;
      }  
    }
  });
}

Comments

Thank You

for your visit