var timer1 = {
time: 150,
startTimer: function () {
"use strict";
$("#btn1").click(function () {
$("#btn1").attr("disabled", true);
$("#btn2").attr("disabled", false);
clearTimeout(interval1);
timer2.startTimer();
$("#btn1").off("click");
});
var interval1 = setInterval(function() {
timer1.time--;
$("#btn1").html(timer1.time);
if (timer1.time <= 0) {
clearInterval(interval1);
$("#btn1").html("Przegrałeś");
return;
}
}, 1000);
}
};
var timer2 = {
time: 150,
startTimer: function () {
"use strict";
$("#btn2").click(function () {
$("#btn2").attr("disabled", true);
$("#btn1").attr("disabled", false);
clearTimeout(interval2);
timer1.startTimer();
$("#btn2").off("click");
});
var interval2 = setInterval(function () {
timer2.time--;
$("#btn2").html(timer2.time);
if (timer2.time <= 0) {
clearInterval(interval2);
$("#btn2").html("Przegrałeś");
return;
}
}, 1000);
}
};
Dlaczego nie zrobisz konstruktora i nie stworzysz za jego pomocą dwóch obiektów? Coś takiego (mogłem coś źle "podpisać" - ale chodzi o zamysł):
function Timer( time, firstElementId, secondElementId ) {
this.time = time;
this.startTimer = function () {
"use strict";
var self = this;
$( firstElement ).click(function () {
$( firstElementId ).attr("disabled", true);
$( secondElementId ).attr("disabled", false);
clearTimeout(interval);
self.startTimer();
$( firstElementId ).off("click");
});
var interval = setInterval(function() {
self.time--;
$( firstElementId ).html(self.time);
if (self.time <= 0) {
clearInterval(interval);
$( firstElementId ).html("Przegrałeś");
return;
}
}, 1000);
}
}
var timer1 = new Timer( 150, "#btn1", "#btn2" );
var timer2 = new Timer( 150, "#btn2", "#btn1" );
Eventy:
$("#btn1").click(function () {
$("#btn1").attr("disabled", true);
$("#btn2").attr("disabled", false);
timer2.startTimer();
$("#btn1").off("click");
});
$("#btn2").click(function () {
$("#btn2").attr("disabled", true);
$("#btn1").attr("disabled", false);
$("#btn2").off("click");
});
Skorzystaj z EventDelegation. Czyli EventListener ustawiasz na rodzica, wewnątrz dajesz powtarzający się kod, a na IF wykonujesz kod specyficzny dla jednego bądź drugiego elementu.