制作脚本循环并自动搜索新值

时间:2018-03-17 21:55:01

标签: javascript

我找不到如何制作脚本循环,我知道我需要setTimeout但我不知道如何实现它,脚本应该在循环中自动搜索新值!

var time = document.getElementById("timer").innerHTML;
if (time < 0.4) {
    var x2 = document.getElementById("2x-total").innerHTML;
    var x3 = document.getElementById("3x-total").innerHTML;
    if (x2 < 2 * x3) {
        var evt = document.createEvent("MouseEvents");
        evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false,
            false, false, false, 0, null);
        var run = document.getElementById("btn2x");
        run.dispatchEvent(evt);
    }
}

function x2a() {       
    document.getElementById("x2p").innerHTML = x2;
}

function x3a() {       
    document.getElementById("x3p").innerHTML = x3;
}
<div id="timer" >00.14</div> //value is always changing

<button id="btn2x"  onclick="x2a()" style="display: block;">2x</button>
<button id="btn3x"  onclick="x3a()" style="display: block;">3x</button>
<span id="2x-total">12000</span>    //value is also changing
<span id="3x-total">7000</span>    //value is also changing
<p id="x2p"></p>
<p id="x3p"></p>

我怎么能让它循环并且还以50~100毫秒的间隔读取“timer”,“2x-total”和“3x-total”的新值!

1 个答案:

答案 0 :(得分:0)

你可以使用setInterval()方法。

将您的代码设为

function wrapperFunction() {
    setInterval(function(){ 
      // your code here which will be executed every 100 ms
    }, 100);
}

现在调用此wrapperFunction()一次,然后其中的代码将每100毫秒执行一次