JQuery停止/暂停声音播放for循环

时间:2017-04-25 13:37:57

标签: javascript jquery loops for-loop audio

我试图让一个for循环重复播放声音,直到变量发生变化:

var ding;
for(ding = 1; ding < 20; ding++) {
    function chamada() {
        jQuery.playSound('components/com_chat/sys/chamada');
    }
    var delay = ding * 2500;
    setTimeout(chamada, delay);
    if (ding == 0){
        break;
    }
}

带有playSound函数的外部.js文件:

 (function($){$.extend({
  playSound: function(){
    return $(
      '<audio autoplay="autoplay" style="display:none;">'
        + '<source src="' + arguments[0] + '.mp3" />'
        + '<source src="' + arguments[0] + '.ogg" />'
        + '<embed src="' + arguments[0] + '.mp3" hidden="true" autostart="true" loop="false" class="playSound" />'
      + '</audio>'
    ).appendTo('body');
  }
  });
  })(jQuery);

EDITED

代码正在运行并将在循环结束时停止,但在我定义ding = 0时单击对话框时不会停止:

  ConfirmDialog('answer');
        function ConfirmDialog(message){
            jQuery('<div></div>').appendTo('body')
                .html('<div class="widget">answering</div>')
                .dialog({
                    modal: true, title: 'answer', zIndex: 10000, autoOpen: true,
                    width: 'auto', resizable: false,
                    buttons: {
                        "Answer": function () {
                            ding = 0;
                        },
                        Cancelar: function () {
                        //...
                        }
                    },
                    close: function (event, ui) {
                        jQuery(this).remove();
                    }
                });
            };
        }

当ding = 0时如何让它停止?

2 个答案:

答案 0 :(得分:2)

var ding;
for(ding = 1; ding < 20; ding++) {
    function chamada() {
        jQuery.playSound('components/com_chat/sys/chamada');
    }
    var delay = ding * 2500;
    setTimeout(chamada, delay);
    if (ding == 0){
        break;
    }
}

在这段代码中,你的ding变量不会减少,所以它实际上不会达到0.

答案 1 :(得分:0)

我用这段代码解决了这个问题:

      var stop_ding = 0;
      var i = 1;   
        function myLoopChamada () { 
           setTimeout(function chamada() {
            jQuery.playSound('components/com_chat/sys/chamada');
              i++;
              console.log('ding '+i);
              if (i < 20) {
                  if(stop_ding != 1){
                    myLoopChamada();
                  }
              }                   
           }, 3000)
        }
        myLoopChamada();

允许for循环每3秒延迟一次,在它一次迭代之前,这就是为什么它无法停止。比我在对话框按钮上添加了答案功能:

 stop_ding = 1;

根据其他问题:

How do I add a delay in a JavaScript loop?

希望它可以帮助别人!