在这里,您可以选择一个日期,它会告诉您该日期的持续时间。但是,如果我选择一个新的日期,那么事情会变得越来越糟糕......一旦选择了新的日期值,我应该怎么做才能重新启动该函数和setInterval?
$(document).ready(function() {
var showOne = new Date();
var showTwo = new Date(2016, 10, 14);
$('#showOne').text(showOne);
$('#showTwo').text(showTwo);
function calcDate(newDater) {
var tickTock = setInterval(function() {
var currentDateSec = $.now() / 1000;
var laterDate = newDater;
// console.log("Later Date: " + laterDate);
var laterDateSec = laterDate / 1000;
var timeLeft = laterDateSec - currentDateSec;
var sLeft = Math.floor(timeLeft) % 60;
var mLeft = Math.floor(timeLeft / (60)) % 60;
var hLeft = Math.floor(timeLeft / (60 * 60)) % 24;
var dLeft = Math.floor(timeLeft / (60 * 60 * 24)) % 7;
var wLeft = Math.floor(timeLeft / (60 * 60 * 24 * 7)) % 4;
var moLeft = Math.floor(timeLeft / (60 * 60 * 24 * 7 * 4));
$('#humandate').text(moLeft + " Month(s) - " + wLeft + " Week(s) - " + dLeft + " Day(s) - " + hLeft + " Hour(s) - " + mLeft + " Mins - " + sLeft + " Sec\(s\)");
}, 1000);
}
$("#datepicker").datepicker({
onSelect: function(dateText, inst) {
var dateAsString = dateText; //the first parameter of this function
var dateAsObject = $(this).datepicker('getDate'); //the getDate method
var date = $("#datepicker").datepicker({
dateFormat: 'dd,MM,yyyy'
}).val();
console.log(dateAsString + " --- " + dateAsObject + " --- " + date);
calcDate(dateAsObject);
}
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js "></script>
<p>Date:
<input type="text" id="datepicker">
</p>
<span id="humandate"></span>
<br/>
&#13;
答案 0 :(得分:0)
您可以通过执行clearInterval(id)
来重置它:
...
var tickTock;
function calcDate(newDater) {
// if you have set it before, clear it.
if (tickTock) {
clearInterval(tickTock);
}
tickTock = setInterval(function() {
....
答案 1 :(得分:0)
将其排序为:
...
function calcDate(newDater) {
$("#datepicker").on( 'blur' , function(){ clearInterval(tickTock); });
var tickTock = setInterval(function() {
...