我试图在加载页面时调用我的简单计时器函数。但它不起作用。我想我在if else
循环的某个地方犯了错误,maby在这里:setTimeout(function(tag, sec), 1000);
我该如何解决?
<script>
document.addEventListener('DOMContentLoaded', function(tag, sec) {
tag = "timerPlace";
sec = 3600;
document.getElementById(tag).innerHTML = "<div id= 'inTime'>" + (sec / 60 >> 0) + 'min ' + sec % 60 + 'sec' + '<br>' + "</div>";
if ((sec / 60 >> 0) != 0 || (sec % 60) != 0) {
setTimeout(function(tag, sec), 1000);
sec -= 1;
} else {
document.getElementById(tag).innerHTML = "Time is over!";
}
}, false);
</script>
<div id="timerPlace"></div>
&#13;
答案 0 :(得分:0)
我更正了你的代码。我仍然不知道你想要达到的目的。 setTimeout回调为空,表示您需要执行的操作。 这是在执行查询中查找元素之前等待DOM准备就绪的正确方法。
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM fully loaded and parsed");
var tag = "timerPlace";
var sec = 3600;
document.getElementById(tag).innerHTML = "<div id= 'inTime'>" + (sec / 60 >> 0) + 'min ' + sec % 60 + 'sec' + '<br>' + "</div>";
if ((sec / 60 >> 0) != 0 || (sec % 60) != 0) {
setTimeout(function() {
//Do something after 1000
}, 1000);
sec -= 1;
} else {
document.getElementById(tag).innerHTML = "Time is over!";
}
});
编辑:
要在页面加载后执行,请使用:
window.addEventListener('load', function () {
//Code to execute after page load
});
答案 1 :(得分:0)
https://jsfiddle.net/Lk963xa0/
用Jquery做了一个例子,不确定这是不是你想要的
JS
$(document).ready(function(){
tag = "timerPlace";
sec = 15;
var timer = function(){
setTimeout(function(){
sec--;
document.getElementById(tag).innerHTML = "<div id= 'inTime'>" + sec + "</div>"
if(sec === 0 ){console.log("time is out"); return}
timer();
}, 1000);
};
timer();
});
HTML
<div id="timerPlace"></div>
答案 2 :(得分:0)
试试这个,
的javascript
// Code goes here
function saysomething() {
alert('say something');
}
document.addEventListener('DOMContentLoaded', function(tag, sec) {
tag = "timerPlace";
sec = 3600;
document.getElementById(tag).innerHTML = "<div id= 'inTime'>" + (sec / 60 >> 0) + 'min ' + sec % 60 + 'sec' + '<br>' + "</div>";
if ((sec / 60 >> 0) != 0 || (sec % 60) != 0) {
// setTimeout(function(tag, sec), 1000);
setTimeout(saysomething, 1000);
sec -= 1;
} else {
document.getElementById(tag).innerHTML = "Time is over!";
}
}, false);
HTML
<body>
<div id="timerPlace"></div>
</body>
或
<script>
//Timer function
window.onload = function() {
myFunction();
};
function myFunction(){
timer('timerPlace',3600);
}
function timer(tag, sec) {
document.getElementById(tag).innerHTML = "<div id= 'inTime'>" +
(sec / 60 >> 0) + 'min ' + sec % 60 + 'sec' + '<br>' + "</div>";
if ((sec / 60 >> 0) != 0 || (sec % 60) != 0) {
setTimeout(function() {
timer(tag, sec);
}, 1000);
sec -= 1;
} else {
document.getElementById(tag).innerHTML = "Time is over!";
}
}
</script>
<div id="timerPlace"></div>
<br>
<br>
<br>
<br>
<!-- Write number of seconds here: onclick="timer('str',...here!...) -->
<button class="button" onclick="timer('timerPlace',3600); style.display = 'none'"> <span>Start Test</span>
</button>
<!-- Place this div where you whant timer to be. -->