Ways to halt the execution of a setTimeout function within a loop

This question is a follow-up from this thread - setTimeout inside a loop, stops script from working

I'm facing an issue with my script that fetches data from an API and stores it in a MongoDB collection. The problem seems to be related to the setTimeout() function, as it prevents the script from running a second time.

For more information on the issue, you can check out this article - Watch Out When Using SetTimeout() in For Loop #JS

Problematic code area:

const callIt = () => {


    fetch(`https://api.binance.com/api/v3/klines?symbol=${symbols[cnt]}&interval=30m&limit=1`)
        .then(res => res.json())
        .then(data => {
            const btcusdtdata = data.map(d => {
                return {
                    Open: parseFloat(d[1]),
                    High: parseFloat(d[2]),
                    Low: parseFloat(d[3]),
                    Close: parseFloat(d[4]),
                    Volume: parseFloat(d[5]),
                    Timespan: 30,
                }
            });
            console.log(btcusdtdata);
            saveToDatebase(btcusdtdata);
            cnt++;
            if (cnt < symbols.length) setTimeout(callIt, 3000);  
        })
        .catch((err) => {
            console.log(err);

        })

};

The script calls the API and processes through an array of symbols. How can I stop the setTimeout() after it has gone through the entire array?

I have tried using clearTimeout(callIt) but it does not seem to work for me.

EDIT1

Error: -

TypeError: data.map is not a function

FULLCODE

var requestPromise = require('request-promise');
const { MongoClient } = require('mongodb');
const schedule = require('node-schedule');
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
const fetch = require("node-fetch");



var symbols = ["ZRXBTC",
    "LENDBTC",
    "AEBTC",
    "AIONBTC",
    "ALGOBTC",
    "ARDRBTC",];
let cnt = 0;
    const callIt = () => {
    fetch(`https://api.binance.com/api/v3/klines?symbol=${symbols[cnt]}&interval=30m&limit=1`)
        .then(res => res.json())
        .then(data => {
            const btcusdtdata = data.map(d => {
                return {
                    Open: parseFloat(d[1]),
                    High: parseFloat(d[2]),
                    Low: parseFloat(d[3]),
                    Close: parseFloat(d[4]),
                    Volume: parseFloat(d[5]),
                    Timespan: 30,
                }
            });
            console.log(btcusdtdata);
            saveToDatebase(btcusdtdata);
            cnt++;
            if (cnt < symbols.length) setTimeout(callIt, 3000);
        })
        .catch((err) => {
            console.log(err);

        })

};
const j = schedule.scheduleJob('*/1 * * * *', callIt)

const saveToDatebase = function(BTCdata) {

    const url = 'mongodb+srv://username:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="36465745454159445276555a4345425344061b075d435844185b59585159525418585342">[email protected]</a>/<dbname>?retryWrites=true&w=majority';

    var today = new Date();
    var date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
    var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
    var dateTime = date + ' ' + time;

    MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }, (err, db) => {
        if (err) throw err;
        const dbo = db.db('CryptoCurrencies');
        const myobj = { Name: symbols[cnt - 1], Array: BTCdata, Date: dateTime };
        dbo.collection(`${symbols[cnt - 1]}`).insertOne(myobj, (error, res) => {
            if (error) throw error;
            console.log('1 document inserted');
            db.close();
        });
    });

};

Answer №1

Your previous query about the script I provided seems to be a bit off, as it actually runs smoothly without the need for clearTimeout. There might be something else causing the issue.

If you wish, you can simply reposition the

if (cnt < symbols.length) setTimeout(callIt, 3000);
line right after db.close();

const symbols = ["ZRXBTC",
"LENDBTC",
"AEBTC",
"AIONBTC",
"ALGOBTC",
"ARDRBTC",];
cnt = 0
const callIt = () => {
  console.log(`https://api.binance.com/api/v3/klines?symbol=${symbols[cnt]}&interval=30m&limit=1`)
  cnt++;
  if (cnt < symbols.length) setTimeout(callIt, 3000);
  else console.log("done!")
};
callIt()

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

What is the best way to create text boxes that change dynamically according to user input using PHP and JavaScript?

Is it possible to modify the code below to allow for dynamic dropdowns to appear based on a number entered by the user in a textbox? I would like the dropdowns to adjust based on the number provided by the user. $query = mysqli_query($con, "SELECT * FRO ...

What is the best way to incorporate interactive columns in DataTables?

I am utilizing jquery datatables to present data. <table class="report-tbl table-bordered" cellspacing="0" width="100%" id="report-tbl"> <thead> <tr> <th></th> ...

What is the most effective method for triggering individual sounds when hovering and clicking?

Hello everyone! I must admit, I am quite new to JavaScript and don't have much knowledge about it. I've shared my question on Reddit as well, so I'm hoping to get some guidance there too. Currently, I am working on editing a website and I w ...

Transferring and displaying messages between PHP scripts

On my page (index.php), I have a simple layout consisting of two DIVs. The left side (#leftDIV) contains a form and another DIV (#messages) for displaying error messages. On the right side, there is another DIV (#mapAJAX) which houses a PHP script responsi ...

What is the best way to send a value using onClick and navigate to a page using href in jquery?

How can I load a page through href and send data using onClick function? Here is the code I have: <a href='doc-menu-2.html' onClick='doc_menu_2(10)'>Item Name</a> <script> myApp.onPageInit('doc-menu-2', fun ...

Creating a union type from an array that is not a literal (using `Object.keys` and `Array.map`)

Can a union be derived from a non-literal array? I attempted the following: const tokens = { "--prefix-apple": "apple", "--prefix-orange": "orange" }; const tokenNames = Object.keys(tokens).map(token => toke ...

Having trouble parsing bytes from a protobuf message in JavaScript

In my current project, I am faced with the task of encoding and decoding bytes within a protobuf message using Javascript. It seems that working with strings is functional, but once I introduce bytes in the message definition, retrieving the data becomes a ...

Retrieve the HTML data from a form created with Angular

Here is an example of an Angular form: <div #myForm [formGroup]="myForm"> <select formControlName="productName" class="form-control"> <option value="">Select</option&g ...

Angular UI validation malfunctioning upon loading of the page

My webpage contains multiple rows with specific validation requirements - at least one Key, Time, and Input must be selected. Initially, the validation works as expected. However, after saving and reloading the page, the default selection for Key, Time, an ...

Data that is loaded asynchronously will not display rendered

I have async data loading via jayson from a server. After the data has finished loading, the boolean "loading" is set to false but my content does not re-render. Even though I can see on the console that the data was loaded correctly. var App = new Vue( ...

How to utilize Vue.js method to retrieve child prop?

In my Vue.js project, I have created two components. The main component uses a child component called NoteRenderer, which includes a prop named data_exchange. My goal is to update this prop from the main component when a button is clicked. I attempted to a ...

Difficulty encountered when displaying JavaScript variable content within HTML in a React component

I'm currently exploring a backend administrative dashboard framework known as admin bro. My current project involves creating a tooltip component, and here is the code I have developed so far. class Textbox extends React.PureComponent { render() { ...

Removing the final element within a nested array: a step-by-step guide

let originalArray=[ [ "Test1", "4", "160496" ], [ "Test2", "6", "38355" ], [ "Test3", "1", "1221781" ], [ " ...

Switching up the image using a dropdown selection menu

I am struggling with updating an image based on the selection made in a dropdown menu. I am quite new to javascript, so I believe there might be a simple issue that I am overlooking. Here is my attempt at doing this: JS: <script type="text/javascript" ...

Tips for customizing bootstrap's fixed navbar-default to ensure that the list items align downwards:

Is it possible to customize the bootstrap fixed navbar-default so that the li elements align downward instead of at the top? If you have any corrections or custom solutions, I'd love to see them! Feel free to share your code on platforms like CodePen, ...

Exploring Ngu-Carousel in Angular 7: Importing JSON data for a dynamic display

After attempting to import data from JSON and display it using ngu-carousel, I encountered an error. The error shows "length of undefined" Subsequently, when I try to click on the previous/next button, another error appears. This error states "innerHTML ...

When working with the Sequelize-Typescript One To Many Association and Repository, a situation may arise where the query returns only one child entity even though there are multiple

Dealing with Sequelize-Typescript, I recently encountered the one-to-many association involving "Album" and "Photos" entities. Each "Album" can have multiple "Photos". Below are the entity codes for reference: Album.ts ` @Table({ timestamps: true, de ...

Verifying Angular (2+?) Compatibility: Opening and Closing Material mat-menu on Hover [GUIDE]

After extensive research, I tried various methods to hover a material menu to display its options. However, the solutions I came across were either too complicated or ineffective. Therefore, I decided to develop my own solution by combining elements of e ...

Incorrect .offset().top calculation detected

Within a webpage, I have multiple sections. Positioned between the first and second section is a navbar menu. As the user scrolls down and the navbar reaches the top of the page, a function is triggered to fix it in place at the top. While this functionali ...

Instructions on creating an individual DropdownIndicator component with React-select for the purpose of reusability in different sections of the project

The code below functions properly when the DropdownIndicator component is kept in the same file. However, I am interested in separating DropdownIndicator into its own file so that it can be reused. This way, it can be used as a separate component and incl ...