最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can i disable the event listener? or having a stop button for it function? - Stack Overflow

programmeradmin1浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 2

Provide 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.

发布评论

评论列表(0)

  1. 暂无评论