Bạn không thể trực tiếp tính giờ còn lại. Bạn có thể lưu trong một biến dấu thời gian khi bộ đếm thời gian được tạo và sử dụng nó để tính toán thời gian thực hiện tiếp theo.
mẫu:
var startTimeMS = 0; // EPOCH Time of event count started
var timerId; // Current timer handler
var timerStep=5000; // Time beetwen calls
// This function starts the timer
function startTimer(){
startTimeMS = (new Date()).getTime();
timerId = setTimeout("eventRaised",timerStep);
}
// This function raises the event when the time has reached and
// Starts a new timer to execute the opeartio again in the defined time
function eventRaised(){
alert('WOP EVENT RAISED!');
clearTimer(timerId); // clear timer
startTimer(); // do again
}
// Gets the number of ms remaining to execute the eventRaised Function
function getRemainingTime(){
return timerStep - ((new Date()).getTime() - startTimeMS);
}
- Đây là tùy chỉnh mẫu mã tạo ra "on the fly".