[javascript] Stop setInterval

I want to stop this interval in the error handler from running repeatedly. Is that possible, and if so, how?

// 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
        }
    });
}

This question is related to javascript jquery html setinterval

The answer is


Use a variable and call clearInterval to stop it.

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);
      }
    });
  }

USE this i hope help you

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");

_x000D_
_x000D_
var flasher_icon = function (obj) {_x000D_
    var classToToggle = obj.classToToggle;_x000D_
    var elem = obj.targetElem;_x000D_
    var oneTime = obj.speed;_x000D_
    var halfFlash = oneTime / 2;_x000D_
    var totalTime = obj.flashingTimes * oneTime;_x000D_
_x000D_
    var interval = setInterval(function(){_x000D_
        elem.addClass(classToToggle);_x000D_
        setTimeout(function() {_x000D_
            elem.removeClass(classToToggle);_x000D_
        }, halfFlash);_x000D_
    }, oneTime);_x000D_
_x000D_
    setTimeout(function() {_x000D_
        clearInterval(interval);_x000D_
    }, totalTime);_x000D_
};_x000D_
_x000D_
flasher_icon({_x000D_
    targetElem: $('#icon-step-1-v1'),_x000D_
    flashingTimes: 3,_x000D_
    classToToggle: 'flasher_icon',_x000D_
    speed: 500_x000D_
});
_x000D_
.steps-icon{_x000D_
    background: #d8d8d8;_x000D_
    color: #000;_x000D_
    font-size: 55px;_x000D_
    padding: 15px;_x000D_
    border-radius: 50%;_x000D_
    margin: 5px;_x000D_
    cursor: pointer;_x000D_
}_x000D_
.flasher_icon{_x000D_
  color: #fff;_x000D_
  background: #820000 !important;_x000D_
  padding-bottom: 15px !important;_x000D_
  padding-top: 15px !important;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> _x000D_
_x000D_
<i class="steps-icon material-icons active" id="icon-step-1-v1" title="" data-toggle="tooltip" data-placement="bottom" data-original-title="Origin Airport">alarm</i>
_x000D_
_x000D_
_x000D_


we can easily stop the set interval by calling clear interval

var count = 0 , i = 5;
var vary = function intervalFunc() {
  count++;
      console.log(count);
    console.log('hello boy');  
    if (count == 10) {
      clearInterval(this);
    }
}

  setInterval(vary, 1500);

You have to assign the returned value of the setInterval function to a variable

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

and then use clearInterval(interval) to clear it again.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to setinterval

How to make `setInterval` behave more in sync, or how to use `setTimeout` instead? How can I pause setInterval() functions? Can clearInterval() be called inside setInterval()? Stop setInterval clearInterval() not working Calculating Page Load Time In JavaScript Javascript setInterval not working How to start and stop/pause setInterval? How do I reset the setInterval timer? jquery function setInterval