如何使用其容器中的属性停止并重新启动 setInterval()
How do I stop and restart setInterval() with attributes from its container
我有这段代码,当我单击 'add' 时,它会向数组中添加一个新人。然后,当我单击 'click' 时,它应该更改数组中那个人的属性,并在 setInterval() 计时器中使用这些新属性(特别是 'interval'),即 'person.hours'.
我希望这样做,因为我需要为每个 'Person'.
单独做
我需要添加代码的主线如下。
//restart interval here with new interval
//so re-run personArray[0].hours with the new personArray[0].interval
但我不确定如何使用对象更新的属性重新开始间隔。
var personArray = [];
function person(name, age, workhours, interval) {
this.name = name;
this.age = age;
this.workhours = workhours;
this.interval = interval;
this.hours = setInterval(function() {
console.log('hello')
}, interval);
}
person.prototype.update = function() {
clearInterval(this.hours);
this.hours = setInterval(function() {
console.log('newhello');
//i want to log the persons name here
console.log(this.name)
}, this.interval);
}
$('#add').click(function() {
personArray.push(new person('fred', 15, 20, 500))
});
$('#click').click(function() {
console.log(personArray[0]);
clearInterval(personArray[0].hours);
personArray[0].interval = 100;
personArray[0].update();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='add'>
add
</button>
<button id='click'>
click me
</button>
这里还有一个fiddle:http://jsfiddle.net/reko91/nVyXS/1726/
可能会让事情更容易测试,提前致谢:)
我不确定你想要达到什么目的,但我相信你必须用新的间隔替换“//此处的重新启动间隔”
像这样的东西:
personArray[0].hours = setInterval(function() {
console.log('hello')
}, personArray[0].interval);
你的代码只能影响数组中的第一个人,但我想你知道 ;)
我有这段代码,当我单击 'add' 时,它会向数组中添加一个新人。然后,当我单击 'click' 时,它应该更改数组中那个人的属性,并在 setInterval() 计时器中使用这些新属性(特别是 'interval'),即 'person.hours'.
我希望这样做,因为我需要为每个 'Person'.
单独做我需要添加代码的主线如下。
//restart interval here with new interval
//so re-run personArray[0].hours with the new personArray[0].interval
但我不确定如何使用对象更新的属性重新开始间隔。
var personArray = [];
function person(name, age, workhours, interval) {
this.name = name;
this.age = age;
this.workhours = workhours;
this.interval = interval;
this.hours = setInterval(function() {
console.log('hello')
}, interval);
}
person.prototype.update = function() {
clearInterval(this.hours);
this.hours = setInterval(function() {
console.log('newhello');
//i want to log the persons name here
console.log(this.name)
}, this.interval);
}
$('#add').click(function() {
personArray.push(new person('fred', 15, 20, 500))
});
$('#click').click(function() {
console.log(personArray[0]);
clearInterval(personArray[0].hours);
personArray[0].interval = 100;
personArray[0].update();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='add'>
add
</button>
<button id='click'>
click me
</button>
这里还有一个fiddle:http://jsfiddle.net/reko91/nVyXS/1726/
可能会让事情更容易测试,提前致谢:)
我不确定你想要达到什么目的,但我相信你必须用新的间隔替换“//此处的重新启动间隔” 像这样的东西:
personArray[0].hours = setInterval(function() {
console.log('hello')
}, personArray[0].interval);
你的代码只能影响数组中的第一个人,但我想你知道 ;)