[英]Multiple timers on a single HTML page
I have the following JavaScript code to update tiles on a page: 我有以下JavaScript代码来更新页面上的图块:
var delayMinimum = 1000;
var delayMaximum = 5000;
function UpdateTiles()
{
var width = 0;
var delay = 0;
var percent = 0;
var divNameLabel = "";
var divNameValue = "";
var divNameProgress = "";
if (Math.floor((Math.random() * 100) + 1) > 30)
{
percent = Math.floor((Math.random() * 100) + 1);
width = Math.floor(80 * percent / 100);
divNameLabel = "DivDashboardTileTemplatesLabel";
divNameValue = "DivDashboardTileTemplatesValue";
divNameProgress = "DivDashboardTileTemplatesProgress";
document.getElementById(divNameValue).innerText = percent.toString() + "%";
$("div#" + divNameProgress).animate({ width: (width.toString() + "px"), }, delayMinimum);
}
if (Math.floor((Math.random() * 100) + 1) > 30)
{
percent = Math.floor((Math.random() * 100) + 1);
width = Math.floor(80 * percent / 100);
divNameLabel = "DivDashboardTileDocumentsLabel";
divNameValue = "DivDashboardTileDocumentsValue";
divNameProgress = "DivDashboardTileDocumentsProgress";
document.getElementById(divNameValue).innerText = percent.toString() + "%";
$("div#" + divNameProgress).animate({ width: (width.toString() + "px"), }, delayMinimum);
}
if (Math.floor((Math.random() * 100) + 1) > 30)
{
percent = Math.floor((Math.random() * 100) + 1);
width = Math.floor(80 * percent / 100);
divNameLabel = "DivDashboardTileFormsLabel";
divNameValue = "DivDashboardTileFormsValue";
divNameProgress = "DivDashboardTileFormsProgress";
document.getElementById(divNameValue).innerText = percent.toString() + "%";
$("div#" + divNameProgress).animate({ width: (width.toString() + "px"), }, delayMinimum);
}
delay = Math.floor((Math.random() * (delayMaximum - delayMinimum)) + delayMinimum);
window.setTimeout(UpdateTiles, delay);
}
$(document).ready(UpdateTiles);
This works but any tiles updated in every iteration are updated all at once. 这可以工作,但每次迭代中更新的所有图块都立即更新。 How could I have independent timers with different intervals for each update? 如何为每个更新设置具有不同间隔的独立计时器?
You only have one timer: window.setTimeout(UpdateTiles, delay)
, add more timers as you need i order to have multiple timers. 您只有一个计时器: window.setTimeout(UpdateTiles, delay)
,根据需要添加更多计时器,以便订购多个计时器。
Use functions instead and set the timeout in each one of them. 请改用函数,并在每个函数中设置超时。
Consider the following JSFiddle as a solution. 考虑以下JSFiddle作为解决方案。
I have simplified it by using 1 function for all 3 calls and they now update at different (random) times. 我通过对所有3个调用使用1个函数简化了它,它们现在在不同的(随机)时间更新。 The key to recalling the update is the following line. 撤消更新的关键是以下几行。
setTimeout(function () {updateTileSet(label,value,progress)}, delay);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.