How can I prevent nested setTimeout functions with identical names from occurring?

Attempting to utilize nested timeOut with the same names, which functions similar to a loop, although not exactly. An example that I tried is:

let i = 1;
setTimeout(function run() {
  func(i);
  setTimeout(run, 100);
}, 100);

which was taken from this link. It's important to note that using interval and loop is not possible as demonstrated in the link.

Below is my current code:

let i = 0;
let x = setTimeout(async function run() {
  if(i == 2) {
    // I intend to completely stop 'x' here
    console.log(i)
    clearTimeout(x);
  }
  try {
    // Some code here e.g:
    console.log(10)
  } catch (err) {
    // Some other code here e.g:
    console.log(err)
  }
  i++;
  x = setTimeout(run, 800);
}, 800);

And the output looks like this:

10
10
2
10
10
... //never stops

I also came across this link, but it doesn't address my specific issue.

Is there anyone who can suggest a way for me to completely stop x?
Thanks in advance.

Answer №1

Avoid relying on the timeout reference within the function, as it may become invalid if the timeout is called. Instead, simply return to exit the function. Here's an example:

let i = 0;
setTimeout(async function run() {
  if (i == 2) {
    console.log(i)
    return
  }
  try {
    //some code here e.g: 
    console.log(10)
  } catch (err) {
    //some other code here e.g:
    console.log(err)
  }
  i++;
  setTimeout(run, 800);
}, 800);

Answer №2

The reason why you need to use return when using clearTimeout is because simply calling clearTimeout(x) will not stop the timeout function since it will just set another timeout with x = setTimeout(run, 800);. By adding return before clearTimeout(x), you effectively stop the timeout function.

    return clearTimeout(x);

In your code snippet, there seems to be no logical reason for clearing the timeout since timeouts only run once. Once a timeout is executed, it is considered complete.

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

Generating forms dynamically using JSON data

Currently, I'm using three nested ng-repeat directives to display multiple questions and their corresponding answers. Everything is displaying correctly so far, but now I need to create a form to save the answers. What would be the best approach to ac ...

Steps to opening a second hyperlink in the same window after initially clicking on Hyperlink1

I'm currently working on a project that involves a main web page with three links: Link1, Link2 and Link3. The requirement is for Link1 to open in a new window (window1) when clicked, while Link2 and Link3 should open in the same window as Link1 (wind ...

Parcel js is encountering difficulties running the same project on Ubuntu

I have encountered an issue with my JavaScript project when trying to run it on Ubuntu using parcel 2 bundler. The code works perfectly fine on Windows, but in Ubuntu, I am facing errors. Despite trying various solutions like cleaning the cache and reinsta ...

What is the best way for library creators to indicate to VSCode which suggested "import" is the correct one?

As a library creator, I have noticed that VSCode often suggests incorrect imports to users. For instance, VSCode typically suggests the following import: import useTranslation from 'next-translate/lib/esm/useTranslation' However, the correct im ...

The re-rendering of a functional component utilizing React.useCallback and React.memo() is occurring

I was delving into React concepts and eager to experiment with some new things. Here are a few questions that crossed my mind: Does every functional child component re-render when the parent state changes, even if it doesn't have any props? It seems ...

"Learn the trick to effectively binding the mousewheel event in Blazor for seamless functionality on the Firefox

We are looking to implement code for a mouse wheel event on a div container. The code below functions correctly in browsers Edge and Chrome: <div id="scroll-container" @onmousewheel="MouseWheelEventHandler"> [...] </div> ...

Tips on creating unit tests for AngularJS attribute-type directives using Jasmine

I have a directive that doesn't use any template or templateUrl. How can I write a unit test for this directive? Below is the code for my directive. var app = angular.module('SampleDirective'); app.directive('sampleContent', [fun ...

Determine in JavaScript if one date occurs exactly one week after another date

Currently, I am tackling a date comparison task for our application. The main objective is to compare the Start Date inputted by the user with the Operator/Region Effective Date, which signifies when a new list of product prices becomes valid. Our aim is t ...

The sorting feature for isotopes is malfunctioning following the addition of a new div element

Isotope was utilized for sorting divs based on attribute values, however, a problem arises when a new div is added or an existing div is edited. The sorting functionality does not work properly in such cases, as the newly created or edited div is placed at ...

Bootstrap 4 Nav Table of Contents with Expand and Collapse Feature

Currently, I am encountering an issue with implementing a button to expand and collapse a "table of contents" in Bootstrap 4. The code I have so far can be viewed here: https://codepen.io/nht910/pen/RwwwyKB Code Snippet: <div class="main-wrapper col- ...

Unveiling concealed content with JQuery

Here is a link to my pen: http://codepen.io/anon/pen/IszKj I am looking to achieve the functionality where clicking on either "any status" or "any date" will reveal a hidden div containing a list of options. My main query is about the best approach to ta ...

Issue with JavaScript function not triggering in Internet Explorer

Here is the code snippet I am working with: <body onLoad="subcatSelection();"> The function that should run on body load is located in a .js file that is included using this code: <script type="text/javascript" src="bincgi/search_lists.js"& ...

Searching for multiple filtered items in Vue.js

When working with Vue js, searching through a list is straightforward. However, when dealing with a large dataset of 1000 records and needing to apply specific filters for user searches, I find myself at a loss. Is there a plugin or method that can help me ...

Can you explain the functionality of the JavaScript code in the index.html file within webpack's react-scripts?

I have been experimenting with dynamically loading a React component into another application that is also a simple React app. However, I am facing challenges getting the index.js file to run properly. While referencing this article for guidance, I notice ...

managing numerous outdated requests on the server

Within my application, there is a map feature that sends a request to the server whenever a user interacts with it, such as zooming in or panning. The issue arises when users perform rapid actions, leading to multiple requests being sent to the server and ...

Nested dropdown menus in Vue.js with multiple levels of nesting

I am currently in the process of developing a Vue single page application and have encountered a challenge with a Vue element I am working on. var appCataloghi = new Vue({ el: '#appCataloghi', data: { cataloghi: oggettoCataloghi.catalog ...

Stealthy Google Recaptcha integrated with a dynamic AJAX form

My website includes an ajax form: <form id="my_form"> <input type="text" id="field1" /> <input type="submit" value="submit" /> </form> I also have this JavaScript code: document.getElementById("my_form").onsubmit = fu ...

Unable to establish successful Ajax connection with PHP function

I'm encountering an issue with submitting a form through ajax and I can't seem to figure it out: Ajax - samepage <script type="text/javascript"> $(document).on('submit','.subscribe',function(e) { $.ajax({ url: &apo ...

transfer chosen data from a text box to a dropdown menu

Looking for: I am in need of a feature where users can input a movie title in a textbox and upon clicking the "move to selectedlist" button, the entered movie title should be added to a dropdown list that displays all the movies selected by the user. Addit ...

Making an AJAX POST request using jQuery to send the current date and time to an ASP

I am working with an ASP.NET Web API endpoint where I need to send POST data. Suppose I want to post the following information: var myObject = { name: "Alice Johnson", age: "29", accountCreated: "CURRENT DATE TIME" }; What is the JavaScript equivalent o ...