javascript - 如何在 if 循环中只执行一次?

标签 javascript jquery html if-statement web

编辑(更具体):

我有以下情况。我正在使用 JavaScript 构建一个实验性合成器界面。我正在使用 howler.js处理音频的插件。 这个想法是,如果满足特定条件,就会播放声音。我有一个数字存储变量,其值通过 iPhone 指南针的标题 改变。 我用compass.js .它有一个名为标题的变量。

$(function(){

    Compass.watch(function (heading) {
      $('.degrees').text(Math.floor(heading) + '°');
      $('#rotate').css('-webkit-transform', 'rotate(' + (-heading) + 'deg)');

       if (heading >= 10 && heading <= 30) {
       sound.play("myFirstSound"); 
       } 
       else if (heading >= 31 && heading <= 60) {
       sound.play("mySecondSound");
       } else { etc etc...
       });
});

即使航向不变,.play 命令也不会执行一次,而是会一遍又一遍地执行,从而导致音频引擎耗尽内存。如何只执行 if 循环中的命令一次?我无法访问指南针功能之外的航向值。我总是收到 var heading does not exist 错误。

最佳答案

取一个 bool 变量,如

var checkOnce= false;
if (myVariable >= 10 && myVariable <= 30) {
checkOnce=true;
    sound.play("myFirstSound"); 
    } 
    else if (myVariable >= 31 && myVariable <= 60) {
checkOnce=true;
    sound.play("mySecondSound");
    } else { etc etc...

在循环中检查 checkOnce 的值。循环将运行直到 checkOnce=false

关于javascript - 如何在 if 循环中只执行一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28813349/

相关文章:

javascript - ES5 中的 block 作用域

html - 我需要 html.Parse() 无法解析的 HTML

html - 水平居中对齐数字

php - 使用 PHP OR/AND

javascript - 字符串未附加到函数中

javascript - EmberJS 和 Rails 4 API 的性能问题

javascript - ui-grid 行高使用 rowHeight : 'auto'

javascript - jQuery 是如何工作的 : I get "Cannot set property xxx of undefined" when trying a similar prototype thing?

jquery - 选择2 : Add and select manual values when using ajax data source

javascript - 在调用所有 promise 后循环遍历 jQuery Deferreds