Ways to cease a setInterval after a specified duration or a specific number of iterations

I have successfully implemented a jQuery code for creating a loop of "changing words" by referring to the solution provided in this Stack Overflow answer: jQuery: Find word and change every few seconds

My question is, how can I stop this loop after a certain amount of time? For example, after 60 seconds or once it has cycled through all the words in the loop?

(function() {

  // List of words to cycle through:
  var words = [
      'Teacher',
      'Principal',
      'Guidance counselor',
      'Teacher',
      'School nurse',
      'Teacher',
      'School psychologist',
      'Administrator'
    ],
    i = 0;

  setInterval(function() {
    $('#dennaText').fadeOut(function() {
      $(this).html(words[i = (i + 1) % words.length]).fadeIn();
    });
    // 2 seconds
  }, 2000);

})();

Answer №1

If you need to halt the process after it has run a specific number of times, simply implement a counter within the interval function. Once the counter reaches the desired number, clear the interval.

For example:

var timesRun = 0;
var interval = setInterval(function(){
    timesRun += 1;
    if(timesRun === 60){
        clearInterval(interval);
    }
    // Carry out desired actions here.
}, 2000); 

If you wish to stop the process after a certain amount of time has passed (e.g. 1 minute), you can use the following approach:

var startTime = new Date().getTime();
var interval = setInterval(function(){
    if(new Date().getTime() - startTime > 60000){
        clearInterval(interval);
        return;
    }
    // Carry out desired actions here.
}, 2000);     

Answer №2

To clear the interval, utilize the clearInterval function. Insert the interval id obtained from the setInterval method into the function.

For instance:

var intervalId = setInterval(function(){
                    ....
                 }, 1000);

To cancel the above interval, use:

clearInterval(intervalId);

You can modify your code as shown below.

(function(){

    // List your words here:
    var words = [
        'Teacher',
        'Principal',
        'Guidance Counselor',
        'Teacher',
        'School Nurse',
        'Teacher',
        'School Psychologist',
        'Administrator'
        ], i = 0;

    var intervalId = setInterval(function(){
        $('#dennaText').fadeOut(function(){
            $(this).html(words[i=(i+1)%words.length]).fadeIn();
            if(i == words.length){//All the words are displayed clear interval
                 clearInterval(intervalId);
            }
        });
       // 2 seconds
    }, 2000);

})();

Answer №3

The easiest fix you can implement:

let intervalId =   setInterval(function() {
    $('#dennaText').fadeOut(function() {
        $(this).html(words[i = (i + 1) % words.length]).fadeIn();
    });
}, 2000); // execute every 2 seconds

setTimeout(function(){
    clearInterval(intervalId);
},10000) // end execution after 10 seconds

Answer №4

Consider utilizing a recursive setTimeout() function instead of setInterval() to prevent any potential race conditions.

let count = 1;
(function fadeInterval(){  
    $('#textElement').fadeOut(function(){
        $(this).html(words[index=(index+1)%words.length]).fadeIn('fast',function(){
            if (count < 30){
                count += 1;
                setTimeout(fadeInterval, 2000);
            }
        });
    });
}());

Answer №5

Consider implementing setTimeout for better control:

(function example(){ // Create a self-invoking function to encapsulate the code
  count = 20; // Number of iterations
  (function iterate(){
    // Perform necessary actions, such as displaying the current count
    document.body.innerHTML = count;

    if( --count ) // 20 iterations * 100ms = 2 seconds
      setTimeout(iterate, 100);
  })();
})();

Answer №6

If you're using VueJs and need to delete a div element after a certain amount of time, here is a code snippet that could be useful for you.

export default {
  name: "Home",
  components: {},
  data() {
    return {
      removeAlert: false,
    };
  },
  methods: {
    removeAlertF() {
      let interval = window.setInterval(() => {
        this.removeAlert = true;
        console.log("done");
        if(true){
          window.clearInterval(interval);
        }
      }, 3000);
    },
  },
  mounted() {
    this.loadData();
    this.removeAlertF();
  },
};
<style>
.remove-alert {
  display: none;
}
</style>
 
 <div
        :class="removeAlert ? 'remove-alert' : ''"
        role="alert"
      >
        Data loaded successfully
      </div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating routes in Node.js after setting up middleware

Currently tackling a project using node.js and encountering a specific issue. After setting up all routes with express (app.get("..", func)), I find myself stuck with a middleware that catches all requests and redirects to a 404-page. The problem arises w ...

What is the best way to ensure that my program runs nonstop?

Is there a way to have my program continuously run? I want it to start over again after completing a process with a 2-second delay. Check out my code snippet below: $(document).ready(function () { var colorBlocks = [ 'skip', 'yell ...

Verify whether a variable includes the tag name "img."

Currently, I am working with a variable that holds user input in HTML format. This input may consist of either plain text or an image. I am looking to determine whether the user has entered an image or just simple text. Here is an example of user entry: t ...

What is the best way to send variables to a jQuery function?

I'm trying to create a form where I can hide unnecessary lines by toggling them with buttons using jQuery. I've managed to start working on a page, but I'm concerned about having to write a separate function for each button, which could beco ...

Issue with bootstrap 4 CDN not functioning on Windows 7 operating system

No matter what I do, the CDN for Bootstrap 4 just won't cooperate with Windows 7. Oddly enough, it works perfectly fine on Windows 8. Here is the CDN link that I'm using: <!doctype html> <html lang="en> <head> <!-- Req ...

Template for Gatsby's alternative layout design

I have recently developed a template for pages that showcase a single product (blog-post.js). However, I now require a different type of page with its own template (category-post.js) to display all products within a specific category. Since the number of c ...

What is the method for copying table data, including input text as cells, to the clipboard without using jQuery?

I have a basic table that looks like this: <table> <thead> <tr> <th>Savings</th> </tr> </thead> <tbody> <tr> <td>Savings <button type="button" (click)=" ...

Error message: Nextjs encounters hydration issue only in the production environment

I've been facing this issue for hours now. I deployed my Next.js application on Vercel and encountered numerous hydration errors there. Interestingly, in my local development environment, I don't experience any errors at all. I came across sugge ...

Tips for implementing a custom filter in an AngularJS JavaScript controller

Can anyone help me with creating a custom filter in an AngularJS JavaScript controller? I need to be able to search for items in an array called segments by their SegmentId. The filter should iterate through the segments array and return the segment that ...

Turn off the ability to debug XHR requests in the developer tools of all web browsers for my website

Is there a method to prevent website users from viewing the communication between my web application and the server via ajax requests? Is there a way to achieve this on my website using code? I want to make sure that the XHR, Ajax calls, and responses ca ...

Problem with full-page navigation sliding in and fading in and out

Upon the user's click on <a href="#slide-nav" class="slide-nav-trigger">, a full-page navigation smoothly slides into view. This animation is triggered by CSS and uses jQuery for event delegation. The Dilemma Instead of abruptly turning on and ...

Alter the font color of text using JavaScript in an HTML document

I am struggling to change the title color in my HTML code below, but the text color does not seem to be changing. How can I make this adjustment? /** * Generate a HTML table with the provided data */ Highcharts.Chart.prototype.generateTable ...

What is the best practice for adding one string to the end of another?

So, is this the best way to concatenate strings in JavaScript? var str = 'Hello'; str += ' World'; While most languages allow for this method of string concatenation, some consider it less efficient. Many programming languages offer a ...

Display the QWebEngineView page only after the completion of a JavaScript script

I am currently in the process of developing a C++ Qt application that includes a web view functionality. My goal is to display a webpage (which I do not have control over and cannot modify) to the user only after running some JavaScript code on it. Despit ...

Switching a react virtualized table from JavaScript to TypeScript can uncover some type-related challenges

I have implemented the following demo in my React project: https://codesandbox.io/s/react-virtualized-table-checbox-stackoverflow-rbl0v?fontsize=14&hidenavigation=1&theme=dark&file=/src/App.js However, I am encountering issues with the code sni ...

What could be the issue with this C# GridView code snippet?

I am facing an issue with a GridView that contains checkboxes. When I try to select a checkbox, I need to retrieve the values from that specific row. The problem lies in the fact that the chk variable in my C# code never evaluates to "true," preventing the ...

Various relationships in Sails.js

Exploring associations in Sails.js beta (version 0.10.0-rc4) has been quite intriguing for me. My current challenge involves linking multiple databases to produce a unified result (utilizing sails-mysql). The association scheme I'm working with invo ...

While my other function remains incomplete, AngularJS $http continues to run without interruption

I'm facing an issue in my AngularJS function where the $http request is being fired before my first function is completed. Here's a sample of how my code looks: $scope.function = function(){ $scope.functionOne(); // This function initializ ...

Ways to modify the color of cells in a table generated from JSON

In developing an HTML table based on JSON data, I have created a university semester map that displays student information including their ID, year, term, and required courses for graduation. While the table is successfully created, I aim to customize the ...

Exploring JavaScript capabilities with Google - managing and updating object names with numbers

After importing JSON data into Google Scripts, I am able to access various objects using the code snippet below: var doc = Utilities.jsonParse(txt); For most objects, I can easily retrieve specific properties like this... var date = doc.data1.dateTime; ...