停止setInterval

Hen*_*son 112 html javascript jquery setinterval

我想在error处理程序中停止此间隔重复运行.这有可能,如果是的话,怎么样?

// example code
$(document).on('ready',function(){
    setInterval(updateDiv,3000);
});

function updateDiv(){
    $.ajax({
        url: 'getContent.php',
        success: function(data){
            $('.square').html(data);
        },
        error: function(){
            $.playSound('oneday.wav');
            $('.square').html('<span style="color:red">Connection problems</span>');
            // I want to stop it here
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

Ror*_*san 222

您需要setInterval在单击处理程序的范围内设置变量的返回值,然后clearInterval()像这样使用:

var interval = null;
$(document).on('ready',function(){
    interval = setInterval(updateDiv,3000);
});

function updateDiv(){
    $.ajax({
        url: 'getContent.php',
        success: function(data){
            $('.square').html(data);
        },
        error: function(){
            clearInterval(interval); // stop the interval
            $.playSound('oneday.wav');
            $('.square').html('<span style="color:red">Connection problems</span>');
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

  • 指向文档的链接:[clearInterval()](https://developer.mozilla.org/zh-CN/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval)和[setInterval()](https://developer.mozilla.org / en-US / docs / Web / API / WindowOrWorkerGlobalScope / setInterval) (3认同)

Chr*_*xon 21

使用变量并调用clearInterval以停止它.

var interval;

$(document).on('ready',function()
  interval = setInterval(updateDiv,3000);
  });

  function updateDiv(){
    $.ajax({
      url: 'getContent.php',
      success: function(data){
        $('.square').html(data);
      },
      error: function(){
        $.playSound('oneday.wav');
        $('.square').html('<span style="color:red">Connection problems</span>');
        // I want to stop it here
        clearInterval(interval);
      }
    });
  }
Run Code Online (Sandbox Code Playgroud)


Mor*_*ler 11

您必须将setInterval函数的返回值分配给变量

var interval;
$(document).on('ready',function(){
    interval = setInterval(updateDiv,3000);
});
Run Code Online (Sandbox Code Playgroud)

然后clearInterval(interval)再次使用它来清除它.


小智 8

使用这个我希望能帮助你

var interval;

function updateDiv(){
    $.ajax({
        url: 'getContent.php',
        success: function(data){
            $('.square').html(data);
        },
        error: function(){
            /* clearInterval(interval); */
            stopinterval(); // stop the interval
            $.playSound('oneday.wav');
            $('.square').html('<span style="color:red">Connection problems</span>');
        }
    });
}

function playinterval(){
  updateDiv(); 
  interval = setInterval(function(){updateDiv();},3000); 
  return false;
}

function stopinterval(){
  clearInterval(interval); 
  return false;
}

$(document)
.on('ready',playinterval)
.on({click:playinterval},"#playinterval")
.on({click:stopinterval},"#stopinterval");
Run Code Online (Sandbox Code Playgroud)