Reputation: 307
I'm trying to get a for loop playing repeatedly a sound until a variable changes:
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;
}
}
The external .js file with playSound function:
(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
Code is working and will stop on the end of the loop, but won't stop when I define ding = 0 clicking on the dialog:
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();
}
});
};
}
How can I make it stop when ding = 0?
Upvotes: 0
Views: 466
Reputation: 307
I solve the problem with this code:
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();
That permits the for loop to delay every 3 seconds, before it was iterate at once, that's why it couldn't be stopped. Than I added on my dialog button answer function:
stop_ding = 1;
As per this other questions:
How do I add a delay in a JavaScript loop?
Hope it can help someone else!
Upvotes: 0
Reputation: 6253
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;
}
}
In this code you have your ding variable increasing not decreasing, so it wont ever actually reach 0.
Upvotes: 2