У меня есть функция jQuery, подобная этой, написанная в стиле ООП:
$.fn.myscript = {
timer: '',
start: function(duration){
var x = 0;
timer = setInterval(function(){
x++;
}, 1000);
},
stop: function(){
clearInterval(timer);
}
}
Во-первых, я вызываю функцию start
, а затем таймер начинает работать. Но когда я звоню stop
функцию он показывает ошибку. В чем проблема? Благодарю!
Используйте this.timer
вместо одного timer
в обоих вызовах:
$.fn.myscript = {
timer: '',
start: function(duration){
var x = 0;
this.timer = setInterval(function(){
x++;
}, 1000);
},
stop: function(){
this.clearInterval(this.timer);
}
}
Предположим, вы используете x, и вы хотите, чтобы у вас была возможность приостановить и возобновить, вот как ваш код может быть:
$.fn.myscript = {
timer: 0, x: 0,
start: function(duration){ // do both start and resume
this.timer = setInterval(function(){
this.x++;
}, 1000);
},
stop: function(){
this.x = 0;
this.clearInterval(this.timer);
},
pause: function(){
this.clearInterval(this.timer);
},
getX: function(){ // use this to get access to x
return this.x;
}
}
this.
, Извините (и спасибо за лаурины).