【问题标题】:Setting function with setInterval() to act at some value使用 setInterval() 设置函数以在某个值处起作用
【发布时间】:2014-09-12 05:05:38
【问题描述】:

我创建了从 1 开始计数的 start() 函数。

我希望它在一段时间后执行某些操作,例如 5 秒。

如何实现?

我已尝试使用 if (timecounter == 5) 但这不起作用。

如果我把 while (timecounter < 5) {continue} 然后从上面的 if 语句,我进入无限循环

function start() {
    setInterval(function () {
        timecounter = timecounter + 1;
        document.getElementById('demo').innerHTML = timecounter;
    }, 1000);

    var clickArea = document.getElementById('clickBox');

    document.getElementById('boxText').style.color = 'white';

    clickArea.addEventListener("click", function () {
        counter += 1;
    });

    if (timecounter === 5) {
        alert('this');
    } //Doesn't work

}

谢谢。

【问题讨论】:

  • 为什么不使用 setTimeout()?
  • if (timecounter === 5) { 将始终为 false,因为您在 setInterval 中设置了 timecounter。该函数的其余部分只会被触发一次。
  • 需要在回调中。

标签: javascript function if-statement while-loop setinterval


【解决方案1】:

就像 cmets 中提到的几个人一样;每当 timecounter 增加时,都需要调用您的测试。 http://jsfiddle.net/John_C/bsAfp/

function start() {
  var timecounter = 0;
  setInterval(function () {
    timecounter = timecounter + 1;
    document.getElementById('demo').innerHTML = timecounter;
    if (timecounter === 5){
      alert('this');
    } //works now
  }, 1000);
}
start(); 

【讨论】:

    【解决方案2】:

    如果您往下看,setInterval 的回调函数是您可以添加支票的地方。每个间隔时间都会调用该回调函数,您将其设置为1000

    function start() {
        setInterval(function () {
            timecounter = timecounter + 1;
            document.getElementById('demo').innerHTML = timecounter;
    
            // this function will be the function that is getting called every second.
            // here you can put in your checks for 5 seconds.
    
            if (timecounter === 5) {
                // do something
            }
        }, 1000);
    
        var clickArea = document.getElementById('clickBox');
    
        document.getElementById('boxText').style.color = 'white';
    
        clickArea.addEventListener("click", function () {
            counter += 1;
        });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多