please help me have a button to stop,pause or disable the function of the accelerometer? Here is my code thanks.
Accelerometer Readings
<script>
function init() {
var accelerometer = document.getElementById('accelerometer');
if(window.DeviceMotionEvent) {
window.addEventListener('devicemotion', function(event) {
var x = parseInt(event.accelerationIncludingGravity.x);
var y = parseInt(event.accelerationIncludingGravity.y);
var z = parseInt(event.accelerationIncludingGravity.z);
var acce = 'Acceleration:<br />';
acce += 'x: ' + x +'<br />y: ' + y + '<br />z: ' + z + ;
accelerometer.innerHTML = acce;
});
}
}
</script>
please help me have a button to stop,pause or disable the function of the accelerometer? Here is my code thanks.
Accelerometer Readings
<script>
function init() {
var accelerometer = document.getElementById('accelerometer');
if(window.DeviceMotionEvent) {
window.addEventListener('devicemotion', function(event) {
var x = parseInt(event.accelerationIncludingGravity.x);
var y = parseInt(event.accelerationIncludingGravity.y);
var z = parseInt(event.accelerationIncludingGravity.z);
var acce = 'Acceleration:<br />';
acce += 'x: ' + x +'<br />y: ' + y + '<br />z: ' + z + ;
accelerometer.innerHTML = acce;
});
}
}
</script>
Share
Improve this question
asked Aug 2, 2016 at 2:14
Ronnel.DRonnel.D
791 gold badge1 silver badge10 bronze badges
0
2 Answers
Reset to default 2Provide a named function reference to .addEventListener()
then use name of function at .removeEventListener()
function handleAccelerationEvent(event) {
var x = parseInt(event.accelerationIncludingGravity.x);
var y = parseInt(event.accelerationIncludingGravity.y);
var z = parseInt(event.accelerationIncludingGravity.z);
var acce = 'Acceleration:<br />';
acce += 'x: ' + x +'<br />y: ' + y + '<br />z: ' + z + ;
accelerometer.innerHTML = acce;
}
function init() {
var accelerometer = document.getElementById('accelerometer');
if(window.DeviceMotionEvent) {
window.addEventListener('devicemotion', handleAccelerationEvent);
}
}
// remove `devicemotion` event referencing `handleAccelerationEvent` function
window.removeEventListener("devicemotion", handleAccelerationEvent)
Method 1: Do not use an anonymous function for a listener: assign it to a variable, so that you can pass it to removeEventListener
.
Method 2: Do not remove a listener; instead, have a flag that determines whether it is active or not. If it is not active at the top of the listener, return without any effect.