为什么setInterval 只执行一次

新手上路,请多包涵
var hour = document.querySelector('.hours');
var minute = document.querySelector('.minutes');
var second = document.querySelector('.seconds');
var nowTime = +new Date();
var defineTime = +new Date('2021-9-25 8:0:0');
var chas = defineTime - nowTime;
fn();
var times = setInterval(fn, 1000);
function fn() {
    var h = parseInt((chas % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var m = parseInt((chas % (1000 * 60 * 60)) / (1000 * 60));
    var s = parseInt((chas % (1000 * 60)) / 1000);
    h = h < 10 ? h = '0' + h : h;
    m = m < 10 ? m = '0' + m : m;
    s = s < 10 ? s = '0' + s : s;
    if (s > 0) {
        hour.innerHTML = h;
        minute.innerHTML = m;
        second.innerHTML = s;
    } else {
        clearInterval(times);

    }
}
阅读 1.6k
2 个回答

if前面打印下,看下s的值

你这代码有问题,修改后代码

var hour = document.querySelector('.hours');
var minute = document.querySelector('.minutes');
var second = document.querySelector('.seconds');
var defineTime = +new Date('2021-9-25 8:0:0');
fn();
var times = setInterval(fn, 1000);
function fn() {
    var nowTime = +new Date();
    var chas = defineTime - nowTime;
    var h = parseInt((chas % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var m = parseInt((chas % (1000 * 60 * 60)) / (1000 * 60));
    var s = parseInt((chas % (1000 * 60)) / 1000);
    h = h < 10 ? h = '0' + h : h;
    m = m < 10 ? m = '0' + m : m;
    s = s < 10 ? s = '0' + s : s;
    console.log(h,m,s);
    if (s > 0) {
        hour.innerHTML = h;
        minute.innerHTML = m;
        second.innerHTML = s;
    } else {
        clearInterval(times);

    }
}

原本代码

var hour = document.querySelector('.hours');
var minute = document.querySelector('.minutes');
var second = document.querySelector('.seconds');
var nowTime = +new Date();
var defineTime = +new Date('2021-9-25 8:0:0');
var chas = defineTime - nowTime;
fn();
var times = setInterval(fn, 1000);
function fn() {
    var h = parseInt((chas % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var m = parseInt((chas % (1000 * 60 * 60)) / (1000 * 60));
    var s = parseInt((chas % (1000 * 60)) / 1000);
    h = h < 10 ? h = '0' + h : h;
    m = m < 10 ? m = '0' + m : m;
    s = s < 10 ? s = '0' + s : s;
    if (s > 0) {
        hour.innerHTML = h;
        minute.innerHTML = m;
        second.innerHTML = s;
    } else {
        clearInterval(times);

    }
}

原本的代码里 chas这个值,不是写在fn中的,nowTime也不是每次在fn中实时计算的,所以,在你原本的fn函数中,chas是固定的,每次setInterval执行的时候h,m,s都不会有啥变化。并不是setInterval不执行,而是你程序的数据问题。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题