JavaScript 和设计模式中的复杂计时器

缥缈止盈
浏览 62回答 1
1回答

慕村225694

使用对象数组跟踪多个计时器的简单演示。只需确定一个易于使用的格式良好的结构来表示数据模型即可。无论是类或函数还是普通对象。我强烈建议重构你的字符串构建。特别是通过字符串串联生成的JavaScript代码。理想情况下,您需要跟踪计时器,startTimer应该返回这些计时器,并且应该可以与数据结构合并并转换以表示每个计时器。现在看来,你最终可能会转向使用全局变量来传递参数。如果这只是一个简单的任务,那么保留一个全局计时器列表可能没什么大不了的。onclick=tag = (x,y,z)=>`<${x} ${y||''}>${z||''}</${x}>`&nbsp; &nbsp; function startTimer(duration, display) {&nbsp; &nbsp; &nbsp; &nbsp; var timer = duration;&nbsp; &nbsp; &nbsp; &nbsp; var minutes, seconds;&nbsp; &nbsp; &nbsp; &nbsp; setInterval(function () {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; minutes = parseInt(timer / 60, 10)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; seconds = parseInt(timer % 60, 10);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; minutes = minutes < 10 ? "0" + minutes : minutes;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; seconds = seconds < 10 ? "0" + seconds : seconds;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; display.textContent = minutes + ":" + seconds;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (--timer < 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; timer = duration;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }, 1000);&nbsp; &nbsp; }&nbsp; &nbsp; var writeSum = function(sums, champ){&nbsp; &nbsp; &nbsp; &nbsp; var height = "height: 25px;";&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; var width = "width: 25px;";&nbsp; &nbsp; &nbsp; &nbsp; var size = "background-size: 25px 25px;";&nbsp; &nbsp; &nbsp; &nbsp; var image = "background-image: url( '../../icons/summoner spells/"+sums.path + "\' );";&nbsp; &nbsp; &nbsp; &nbsp; var display = "display: inline;";&nbsp; &nbsp; &nbsp; &nbsp; var click = "onclick =\"startTimer("+ sums.cd+", document.getElementById('"+ champ.name+ sums.name+"'\)\)\" ";&nbsp; &nbsp; &nbsp; &nbsp; return tag("div","",tag("button", click+style(height+width+image+size),"")+ tag("p","id = \""+champ.name+ sums.name + "\" "+style(display),"Ready"));&nbsp; &nbsp; };&nbsp; &nbsp; function style(x){return `style="${x}"`}let entities = [&nbsp; &nbsp; {sums: {path:'spath1',cd:'10',name:'sname1'}, champ: {name:'cname1'}},&nbsp; &nbsp; {sums: {path:'spath2',cd:'10',name:'sname2'}, champ: {name:'cname2'}},&nbsp; &nbsp; {sums: {path:'spath3',cd:'10',name:'sname3'}, champ: {name:'cname3'}},&nbsp; &nbsp; {sums: {path:'spath4',cd:'10',name:'sname4'}, champ: {name:'cname4'}}]document.body.innerHTML=entities.map(({sums, champ})=>writeSum(sums, champ)).join('')展开代码段
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript