Nếu bằng cách "khởi động lại", bạn có nghĩa là để bắt đầu một khoảng thời gian 4 giây mới tại thời điểm này, sau đó bạn phải dừng lại và khởi động lại bộ hẹn giờ.
function myFn() {console.log('idle');}
var myTimer = setInterval(myFn, 4000);
// Then, later at some future time,
// to restart a new 4 second interval starting at this exact moment in time
clearInterval(myTimer);
myTimer = setInterval(myFn, 4000);
Bạn cũng có thể sử dụng một chút đối tượng hẹn giờ mà cung cấp một tính năng thiết lập lại:
function Timer(fn, t) {
var timerObj = setInterval(fn, t);
this.stop = function() {
if (timerObj) {
clearInterval(timerObj);
timerObj = null;
}
return this;
}
// start timer using current settings (if it's not already running)
this.start = function() {
if (!timerObj) {
this.stop();
timerObj = setInterval(fn, t);
}
return this;
}
// start with new interval, stop current interval
this.reset = function(newT) {
t = newT;
return this.stop().start();
}
}
Cách sử dụng:
var timer = new Timer(function() {
// your function here
}, 5000);
// switch interval to 10 seconds
timer.reset(10000);
// stop the timer
timer.stop();
// start the timer
timer.start();
bản demo làm việc: https://jsfiddle.net/jfriend00/t17vz506/
Đối tượng đẹp Tôi luôn cảm thấy vui khi tôi thấy ai đó sử dụng OOP trong javascript! Cảm ơn bạn! – Fortin