JavaScript backbone's setTimeOut feature

I am encountering an issue with the setTimeOut method that calls a function and sets a delay. The function should be called repeatedly after each request is completed, but it only runs once. It works fine without using backbone.js, but I am not sure why it doesn't work after integration with backbone.js. Any assistance would be greatly appreciated!

Here is a function in the client that sends a GET request to the server to retrieve data. The request runs at a time interval determined by the server. When new data arrives, the client fetches it and the request restarts.

    getRequest:function() {
        var XHR = $.ajax({
            url: '/nextdocument',
            type: 'GET',
            async: true,
            cache: false,
            timeout: 11000, 
            success:function(data) {
                var name = data.description;
                var price = data.price;
                console.log("read--> " + name + price);
                setTimeout("this.getRequest", 1000);
                if (data.ok == "true") {
                    data["ok"] = data.ok;
                    $.ajax(
                        {
                            url: "/customerdone",
                            data: JSON.stringify(data),
                            processData: false,
                            type: 'POST',
                            contentType: 'application/json'
                        }
                    )
                }else{
                    //no document if no read in
                    console.log("error--> " + data.errorMessage)
                }
            }
        })
        return XHR;
    }

Answer №1

The issue arises from utilizing the keyword "this" within your setTimeout function. The problem lies in the fact that when the timer triggers the function you are attempting to access, "this" will actually refer to the global object.

As recommended by others, it is crucial to provide a genuine function as an argument to your timer instead of a string. This way, you can easily reference any function from any object as needed.

Answer №2

It's possible that the function getRequest is not being called. This could be because you are passing a string "this.getRequest" to the setTimeout function instead of an actual function. It's generally a good practice to pass functions instead of strings in situations like this. Using 'this' in this context might be causing the issue. You can try the following approach instead:

getRequest:function() {
    var fn = arguments.callee;
    var XHR = $.ajax({
        url: '/nextdocument',
        type: 'GET',
        async: true,
        cache: false,
        timeout: 11000, 
        success:function(data) {
            var name = data.description;
            var price = data.price;
            console.log("read--> " + name + price);
            setTimeout(fn, 1000);
            if (data.ok == "true") {
                data["ok"] = data.ok;
                $.ajax(
                    {
                        url: "/customerdone",
                        data: JSON.stringify(data),
                        processData: false,
                        type: 'POST',
                        contentType: 'application/json'
                    }
                )
            }else{
                //no document if no read in
                console.log("error--> " + data.errorMessage)
            }
        }
    })
    return XHR;
}

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

How to handle the discrepancy between NextJS exporting files with a .html extension, yet in the <Link> component there is no .html specified

I have been working on my NextJS application and I've realized that all the links within it are built using the <Link href="/my-page"><a>My page</a></Link> component. After exporting the app to generate a static site, ...

Promise.allSettled() - Improving resilience through retry mechanisms for concurrent asynchronous requests

TL;DR: I'm seeking advice on how to handle multiple promise rejections and retry them a specified number of times when using Promise.allSettled() for various asynchronous calls. Having come across this article: I was intrigued by the following state ...

When ran automatically as a cron job, the JavaScript script fails to establish a connection with MongoDB

As I connect to mongodb (on a Ubuntu machine) from a js script, everything runs smoothly when I execute the command from the command line (node <name of the script>). However, when I try executing the same command from cron, the connection times out: ...

Ensure that your script is set to execute only once all external content has been loaded successfully

Without diving into the usual question of how to execute a script after a page has finished loading, I have an example set up here (check out this fiddle): $.getScript("http://platform.linkedin.com/in.js").done(function() { alert('hello'); ...

Exploring the Use of data- Attributes in SVG Circle Elements

Looking for a way to dynamically update the color of a Circle element in your SVG when it is clicked? You can achieve this by using jQuery's .css() method in conjunction with the data-* attribute. CHECK OUT AN EXAMPLE: STYLING IN CSS svg { height ...

The series attribute cannot be located within the reactD3Basic object in ReactD3

Recently, I attempted to integrate the reactd3 library into my project and encountered an issue: Uncaught TypeError: (0 , _reactD3Basic.series) is not a function This error is specifically pointing to this line in the library code: var chartSeriesData = ...

Exploring the capabilities of Google Apps Script for looping and generating output

I have two spreadsheets named rawData and processedData. The content of rawData is as follows: Status Title Options Live Title1 Option1, Option2, Option3, Option4 Live Title2 Option1, Option2, Option3, Option4, Option5 Live Title3 Option1, O ...

The dynamic change of a required field property does not occur

I am facing an issue where one of my fields in the form should be mandatory or not based on a boolean variable. Even if the variable changes, the field always remains required. I'm puzzled about why my expressionProperties templateOptions.required is ...

Having trouble persisting drop down values to the database in Symfony2 when utilizing ajax

I designed a registration page that requires users to input their country details. Users can select the country from a dropdown menu, which dynamically populates the states dropdown list using Ajax. The same process applies for the cities list. I was able ...

The issue with mediaDevices.getUserMedia not functioning properly in Safari 11 on iOS 11 persists, as the video output appears as a

I'm having trouble understanding why my code is not working. I've read that Safari 11 should be compatible with getUserMedia APIs from iOS 11, but for some reason it's not functioning as expected. My aim is to capture a QR code in a live str ...

Arranging JSON array elements in order

Currently in the process of creating an application with jQuery mobile. The data is stored in a JSON file: [{ "title": "title you desire", "url" : "thisistheurl.com" },{ "title": "title you desire", "url" : "thisistheurl.com" },{ "title": "title ...

PHP generating JSON data

In my database, I have data stored like this: COl1 | COL2 fruit | apple, grape, berry vegetable | tom, pot, leaf When I query for fruit, I would like the output of echo json_encode($data) to be formatted as follows: [ {input: "fruit", target: ...

Notification within the conditional statement in React JS

I am working on validating phone number input within a React JS component using an if/else statement. If the user enters letters instead of numbers, I want to display a message saying "please check phone number". While I have been able to create a function ...

Extracting data from an excel spreadsheet and transferring the precise characters to a JSON document

I have a problem with character encoding when reading values from an Excel sheet and writing them to a JSON file. The characters are not being written as they appear in the original text. For example: If the text is "Молба", it gets converted to "&b ...

When making a fetch call in React, the response is the index.html file but Chrome displays an error saying Uncaught (in promise) SyntaxError: Unexpected token < in JSON

I have been encountering an issue while trying to retrieve data from my local express server and displaying it using React. The problem appears to be that instead of fetching the data, the index.html of the React app is being returned. In the network tab o ...

Error: Firebase is throwing an error stating that it cannot access the length property of an undefined property

I need help establishing a connection with Firebase. Here is the code snippet from firebase.js: import * as firebase from "firebase/compat/app"; const firebaseConfig = { apiKey: "***", authDomain: "***", projectId: &qu ...

ConfirmUsername is immutable | TypeScript paired with Jest and Enzyme

Currently, I am experimenting with Jest and Enzyme on my React-TS project to test a small utility function. While working on a JS file within the project, I encountered the following error: "validateUsername" is read-only. Here is the code for the utilit ...

Add a checkbox element to a web API using ReactJS

I'm currently learning react and encountering an issue with checkboxes that I can't seem to resolve. I am working on a modal for updating and inserting data in a .net core web api, which is functioning correctly. However, within the app, I'm ...

Python encountered an issue while trying to read the JSON file. It is expected to find a value at line 1, column 1 (

I'm encountering an issue while trying to read JSON data from a file in Python. Can someone help me figure out what I'm doing wrong? [ { "name": "Alex C", "age": 2, "city": &quo ...

Is there a way to implement a feature that automatically closes the chatbot when the user clicks outside of it?

Here is an example of my HTML code: <div class="chatbot chatbot--closed "> <div class="chatbot__header"> <p><strong>Got a question?</strong> <span class="u-text-highlight">Ask Harry</span></p> < ...