【发布时间】:2021-07-24 20:56:16
【问题描述】:
函数 totsessie2stopt();在这里可以正常运行:https://jsfiddle.net/szua2fed/
// Begin countdown
function totsessie2stopt() {
(function() {
var start = new Date;
start.setHours(23, 30, 0); // 11pm
function pad(num) {
return ("0" + parseInt(num)).substr(-2);
}
function tick() {
var now = new Date;
if (now > start) { // too late, go to tomorrow
start.setDate(start.getDate() + 1);
}
var remain = ((start - now) / 1000);
var hh = pad((remain / 60 / 60) % 60);
var mm = pad((remain / 60) % 60);
var ss = pad(remain % 60);
document.getElementById('time').innerHTML = " Still " + hh + " hours and " + mm + " minutes and " + ss + " seconds to go!";
setTimeout(tick, 1000);
}
document.addEventListener('DOMContentLoaded', tick);
})();
}
totsessie2stopt();
// End countdown
这只是一个倒计时。
问题是当我把这个函数放在 setTimeout(function() { ... } 这里时,它不会运行:https://jsfiddle.net/cx59L387/ 这个函数应该在第 2 行的给定时间运行。
setTimeout(function() {
document.getElementById("test1").innerHTML = "This message will display at a given time on line 2!";
// Begin countdown
function totsessie2stopt() {
(function() {
var start = new Date;
start.setHours(23, 30, 0); // 11pm
function pad(num) {
return ("0" + parseInt(num)).substr(-2);
}
function tick() {
var now = new Date;
if (now > start) { // too late, go to tomorrow
start.setDate(start.getDate() + 1);
}
var remain = ((start - now) / 1000);
var hh = pad((remain / 60 / 60) % 60);
var mm = pad((remain / 60) % 60);
var ss = pad(remain % 60);
document.getElementById('time').innerHTML = " Still " + hh + " hours and " + mm + " minutes and " + ss + " seconds to go!";
setTimeout(tick, 1000);
}
document.addEventListener('DOMContentLoaded', tick);
})();
}
totsessie2stopt();
// End countdown
}, totsessie1);
在 setTimeout(function() { ... } 内部,其他函数工作正常。我已经苦苦挣扎了几天,想知道如何在其中运行倒数计时器。有人可以帮忙吗?
非常感谢!
网格
【问题讨论】:
-
totsessie1变量的值很大,所以超时会在很长一段时间后执行 -
@AlexandroPalacios setTimeout(function() { ... } 中的其他函数运行正常,没有延迟,我不知道你到底是什么意思
-
他们说的是你有
setTimeout(function, totsessie1),其中totsessie1是一个变量。在提供的未定义变量的代码中,hens settimeout 不会触发。 -
@vanown 我相信它会触发,因为第 7 行会运行,也许我们彼此误解了?你有什么建议我将如何运行第 37 行吗?
标签: javascript scope settimeout