gpt4 book ai didi

javascript - 如何创建点击事件以显示设置的间隔时间

转载 作者:行者123 更新时间:2023-11-30 14:22:08 25 4
gpt4 key购买 nike

我有一个 Javascript setInterval 函数设置为像计时器一样显示。我想在单击“下一步”按钮时显示计时器上的时间,以便用户可以看到他们在某个页面上花费了多长时间。我不确定如何将 setInterval 与点击事件联系起来。这就是我所拥有的,但它不起作用。

let timerId = setInterval(function () {
document.getElementById("seconds").innerHTML = pad(++sec % 60);
document.getElementById("minutes").innerHTML = pad(parseInt(sec / 60, 10));
}, 1000);
function myFunction() {
alert document.getElementById("timerId").innerHTML = "Time passed: " + timerId);
}

最佳答案

这应该可以解决您的问题。

var initialTime = new Date().getTime();
var timeSpent='0:00';
var timeElement = document.getElementById("time");

timeElement.innerHTML = timeSpent;

let timerId = setInterval(function () {
var currentTime = new Date().getTime();
timeSpent = millisToMinutesAndSeconds(currentTime - initialTime)
timeElement.innerHTML = timeSpent;
}, 1000);

function millisToMinutesAndSeconds(millis) {
var minutes = Math.floor(millis / 60000);
var seconds = ((millis % 60000) / 1000).toFixed(0);
return minutes + ":" + (seconds < 10 ? '0' : '') + seconds;
}

function alertFn(){alert(timeSpent)}
document.getElementById("rightButton").addEventListener('click',alertFn);

document.getElementById("wrongButton").addEventListener('click',alertFn);
<h1 id="time"></h1>
<button id="rightButton">Right</button>
<button id="wrongButton">Wrong</button>

关于javascript - 如何创建点击事件以显示设置的间隔时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52580949/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com