The new APIs provided in modern browsers are increasingly leaning towards mobile phone applications rather than traditional desktop applications, such as the JavaScript geolocation information API. Another JavaScript API that is only targeted at mobile applications is the Vibration API. Obviously, this API allows mobile programmers to use JavaScript to call the vibration function of the phone and set the vibration method and duration.
Related learning recommendations: javascript video tutorial
A good habit Just check whether your current application environment and browser support the vibration API before using it. The following is the detection method:
// Standards ftw! var supportsVibrate = "vibrate" in navigator;
There is only one API about vibration in the window.navigator
object: vibrate
.
This navigator.vibrate
function can accept a numeric parameter or a numeric array. When using an array parameter, the odd-digit value It is the number of seconds to vibrate, and the even-numbered digits are the number of waiting seconds.
// 振动1秒 navigator.vibrate(1000); // 振动多次 // 参数分别是震动3秒,等待2秒,然后振动1秒 navigator.vibrate([3000, 2000, 1000]);
If you want to stop vibrating, you only need to pass 0 or an empty array to the navigator.vibrate
method:
// 停止振动 navigator.vibrate(0); navigator.vibrate([]);
It should be reminded that, for # The call to the ##navigator.vibrate method will not cause the phone to vibrate cyclically; when the parameter is a number, the vibration will occur once and then stop. When the parameter is an array, the vibration will vibrate according to the value in the array, and then stop vibrating.
setInterval and
clearInterval methods to produce the effect of making the phone continuously vibrate:
var vibrateInterval; // Starts vibration at passed in level function startVibrate(duration) { navigator.vibrate(duration); } // Stops vibration function stopVibrate() { // Clear interval and stop persistent vibrating if(vibrateInterval) clearInterval(vibrateInterval); navigator.vibrate(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 is the detailed content of Learn JavaScript mobile phone vibration API. For more information, please follow other related articles on the PHP Chinese website!