javascript - Javascript双定时器
问题描述
所以我想设置一个香草 JavaScript 来显示消息屏幕文本 30-40 秒,然后显示不同的文本 10 秒。第一条消息应按特定顺序更改(即.. hello, world, i ,love java, script)。并循环通过。我试图把它放在一个带有计时器的数组中,但运气不好不能让计时器在 30 到 10 秒之间振荡。所以,即……你好 30 秒,然后世界 10 秒,然后我爱 30 秒,依此类推。目前我正在关注这个例子,但我宁愿不做数学,必须有一个更干净更好的方法。 https://www.w3schools.com/jsref/met_win_settimeout.asp
这就是我现在正在做的。缩写
function timedText() {
setTimeout(myTimeout1, 10000) setTimeout(myTimeout2, 30000) setTimeout(myTimeout3, 40000)
}
function myTimeout1() {
document.getElementById("tebatademo").innerHTML = "<h2 style='background-color: yellow; color: black; text-align: center;'>Mountin Climbers</h2>";
}
function myTimeout2() {
document.getElementById("tebatademo").innerHTML = "<h2 style='background-color: red; color: white; text-align: center;'>REST</h2>";
}
function myTimeout3() {
document.getElementById("tebatademo").innerHTML = "<h2 style='background-color: yellow; color: black; text-align: center;'>Inch Worms</h2>";
}
解决方案
为什么不只有两个功能,一个设置另一个,反之亦然?
function one() {
window.alert('Messsage One')
setTimeout(two, 10*1000);
}
function two() {
window.alert('Message two');
setTimeout(one, 30*1000);
}
setTimeout(two, 30*1000);
显然,您可以将window.alert
调用更改为实际用于显示文本的任何方法。
编辑好的,根据您的要求进行更新。如果你想要一个单词数组循环,并改变时间,我已经这样做了。给定 HTML:
<div id='msgBox'></div>
您可以设置一个数组和一个函数以从该数组中显示,如下所示:
var msgBox = document.getElementById('msgBox');
var messages = ['hello', 'world', 'i' ,'love', 'java', 'script']
function updateMessage() {
// take the first word out of the array and store it in the msg variable
var msg = messages.shift();
// set the div content to the word
msgBox.innerHTML = msg;
// pick a duration based on if the remaining array length is odd or even
var duration = messages.length % 2 ? 10 * 1000 : 30 * 1000
// queue up the next message update
setTimeout(updateMessage, duration)
}
setTimeout(updateMessage, 10*1000)
显然,您可以随意调整持续时间位;我只是做了一个模运算,所以基本上如果数组长度是偶数,你等待 10 秒,如果是奇数,你等待 30 秒。
同样,如果您想更新内部内容以包含其他信息(例如,您有一个具有各种样式的 h2),您可以将整个字符串放入数组中,或者您可以使用类似于我的持续时间逻辑的东西来选择正确的包装器.
推荐阅读
- c++ - 是否允许将指向模板函数的指针传递给 C 库?(作为回调)
- pdf-reactor - 如何使用 REST API PdfReactor / MS Flow Post Request
- sql - SSAS 表格多维数据集中的舍入问题
- pandas - 根据 groupby 移位更改列的值并创建新列 - Pandas
- couchdb - CouchDB 在重新启动时不会散列管理员密码
- java - 使用 user.reauthenticate 更新 Firebase 身份验证密码
- javascript - window.focus() 不适用于所有 IOS 浏览器中的现有选项卡
- salesforce - 在 Cybersource Flex Microform 上发送/添加 CVV/CVN 字段
- python - Python检查两个数字是否在两个数字之间
- c++ - 为什么 auto&& 可以绑定左值,而 int&& 不能?