Vibrate mobile device with JavaScript

Tram Ho

Mobile device vibration makes the user experience better, for example, notifications with messages, new posts …

Using:

Syntax:

The device can vibrate using navigator.vibrate() .

For example:

  • To perform the vibration  We pass the parameter in units of miliseconds. For example:

  • To perform multiple vibrations, pass an integer array, [[vibration time] [ break time ] [vibration time] [ break time ] …]: window.navigator.vibrate([400, 100, 300, 100]);

The above code will perform vibration, break 400, 100, 300, 100 seconds.

Cancel vibration:

Pass a value function 0

window.navigator.vibrate(0);

Return value:

The navigator.vibrate function returns the boolean value

  • false: if the parameter passed is not valid.
  • true: if the parameter passed is valid.

Note:

  • If one vibrate function is executing, another vibrate function is called, the first one will be canceled and the second one will start executing.
  • If the vibrating time is too long, the browser will vibrate for the preset time and leave the rest.
  • This thread function will only work when the device has a vibration sensor.

Supported Browsers:

  • Google Chrome 32 and above
  • Firefox 16 and above
Share the news now

Source : Viblo