为什么计时器没有在我的 JavaScript 代码中运行? [重复]

问题描述 投票:0回答:1

我正在尝试向计算数字因数的 JavaScript 函数添加一个计时器。我想每秒记录经过的秒数,直到函数返回。这是我的代码:

var getFactors = N => {
    let cnt = 0;
    for (let index = 1; index <= N; index++) {
        if (N % index === 0) cnt++;
    }
    return cnt;
}

function logSeconds() {
    const elapsedTime = Math.floor((Date.now() - startTime) / 1000);
    console.log(`Elapsed time: ${elapsedTime} seconds.`);
}

let startTime = Date.now(); // start time
const loggingInterval = setInterval(logSeconds, 1000);
setTimeout(() => {
    console.log(getFactors(10000000000)); // function called with value of 10^9
    clearInterval(loggingInterval); // terminating the timer
}, 0);

但是,计时器似乎不工作,我传递的值是 10^9。该函数正确运行并记录了因素的数量,但计时器不记录任何内容。我做错了什么?

需要注意的是,这不是针对因子优化代码。

如有任何帮助或建议,我将不胜感激。谢谢!

javascript settimeout
1个回答
-3
投票
    function getFactors(N) {
    let cnt = 0;
    for (let index = 1; index <= N; index++) {
        if (N % index === 0) cnt++;
    }
    return cnt;
}

function logSeconds(startTime) {
    const elapsedTime = Math.floor((Date.now() - startTime) / 1000);
    console.log(`Elapsed time: ${elapsedTime} seconds.`);
}

function calculateFactorsWithTimer(N) {
    let startTime = Date.now();
    const loggingInterval = setInterval(() => logSeconds(startTime), 1000);
    const factors = getFactors(N);
    clearInterval(loggingInterval);
    return factors;
}

console.log(calculateFactorsWithTimer(10000000000)); // call with value of 10^9

试一试

© www.soinside.com 2019 - 2024. All rights reserved.