SoFunction
Updated on 2025-04-03

JavaScript mobile phone vibration API

Obviously, this API allows mobile programmers to use JavaScript to call the phone's vibration function and can set the way and duration of vibration.
Determine the browser's support for the vibration API

A good habit is to check whether your current application environment and browser support vibration API before using it. Here is the detection method:

// Standards ftw!
var supportsVibrate = "vibrate" in navigator;

There is only one API about vibration in the object: vibrate.

Basic application of vibration API

This function can accept a numeric parameter or an array of numbers. When using array parameters, the value of odd digits is the number of vibration seconds, and the even digits are the number of waiting seconds.

// Vibrate for 1 second(1000);

// Vibrate multiple times// The parameters are vibration for 3 seconds, wait for 2 seconds, and then vibrate for 1 second.([3000, 2000, 1000]);

If you want to stop the vibration, you just need to pass 0 into the method, or an empty array:

// Stop vibration(0);
([]);

It should be noted that calling the method will not cause the mobile phone to vibrate in a loop; when the parameter is a number, the vibration occurs once afterwards and then stops. When the parameter is an array, the vibration will vibrate according to the value in the array, and then stop vibrating.

Continuous vibration

We can simply use the setInterval and clearInterval methods to create the effect of continuously vibrating the phone:

var vibrateInterval;

// Starts vibration at passed in level
function startVibrate(duration) {
 (duration);
}

// Stops vibration
function stopVibrate() {
 // Clear interval and stop persistent vibrating 
 if(vibrateInterval) clearInterval(vibrateInterval);
 (0);
}

// Start persistent vibration at given duration and interval
// Assumes a number value is given
function startPeristentVibrate(duration, interval) {
 vibrateInterval = setInterval(function() {
 startVibrate(duration);
 }, interval);
}

The above code is just for the case where the vibration parameter is a number. If the parameter is an array, you also need to calculate its total duration and then loop according to its characteristics.

Scenarios using Vibration API

This API is obviously aimed at mobile phone devices. When developing mobile phone WEB mobile applications, it is a good warning tool, and this vibration function is an indispensable and good technology when developing web games or multimedia applications. For example, when a user is playing your WEB game with a mobile phone, when an explosion occurs in the game and you let the phone vibrate, isn’t it an excellent user experience?

How do you feel about this JavaScript vibration API? Do you think it will become popular soon? Or is it not very useful?