【问题标题】:Flickering and glitching occuring when setInterval used in loop在循环中使用 setInterval 时出现闪烁和故障
【发布时间】:2017-11-30 10:15:42
【问题描述】:
  function startTimer(duration, activity) {
    function countdown() {
      if ((duration - 1) > 0) {
        duration--;
        $("#timer").html(convertNumbers(duration))
      } else {
        if (activity === "session") {
          startBreak();
        } else {
          startSession();
        }
      }    
    }

    setInterval(countdown, 1000) 
}

function startSession() {
    var time = parseInt(($("#session_time").text()), 10);
    startTimer(time * 60, "session");
    $("#activity").html("Session");
}

function startBreak() {
    var time = parseInt(($("#break_time").text()), 10);
    startTimer(time * 60, "break");
    $("#activity").html("Break");
}

开始按钮:

$("#start").click(function() {
  startSession();
});

我正在使用 setInterval 制作一个番茄钟,它每秒运行一次以递减一秒。当按下开始按钮时,startSession()函数抓取时间并调用startTimer()函数,当持续时间为0时,该函数指向setBreak()。

理想情况下,它会在 startSession 和 startBreak 之间交替,但在初始倒计时后,“#timer”中设置的文本(剩余时间)中会出现闪烁和随机数。这可能与 startTimer() 调用 startBreak() 时没有结束 Interval 有关。

【问题讨论】:

  • This might have something to do with not ending the Interval - 你是对的,你需要使用clearInterval ...你还需要保存间隔ID以便你可以清除它

标签: javascript


【解决方案1】:

您永远不会清除初始间隔,因此当中断发生时,两个间隔同时运行。

setInterval 返回一个间隔 ID,您可以将其传递给 clearInterval() 以再次停止它。

var timer = setInterval(function () {
    console.log('A second has passed!');
}, 1000});

setTimeout(function () {
    clearInterval(timer);
    console.log('Seconds no longer passes');
}, 10 * 1000);

有关详细信息,请参阅 setInterval 和 clearInterval 的文档。

【讨论】:

    【解决方案2】:
    <?php 
     $no1=0;
    foreach($location_data as $last_data){ 
                          
            if($location[0]->depth_unit=="meter"){
              $depth_drilled=($last_data->end_depth - $last_data->start_depth)*3.28;
              $acceptable_loss=((12.25*12.25)/1029.4*($depth_drilled)/6.28);
          }
          else{
              $depth_drilled=($last_data->end_depth - $last_data->start_depth);
              $acceptable_loss=(12.25*12.25)/1029.4*($depth_drilled);
          }
          ?>
          setInterval(function(){
      <?php  if($last_data->shaker_loss_value < $acceptable_loss ){ ?>
        chart.options.data[3].dataPoints[<?php echo $no1; ?>].markerColor = "transparent";
     <?php } else { ?>
        chart.options.data[3].dataPoints[<?php echo $no1; ?>].markerColor = "red";
          chart.options.data[3].dataPoints[<?php echo $no1; ?>].markerType = "triangle";
          <?php  } ?>
     chart.render();
     },<?php echo $no1; ?> * 1000);
     <?php
     $no1++;
    }  ?>
    

    我需要闪烁我的 canvas.js 标记,祝你好运

    【讨论】:

      猜你喜欢
      • 2018-04-23
      • 2020-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-12
      • 2021-01-17
      相关资源
      最近更新 更多