Things, their examples and the impact of setTimeOut

I'm currently delving into object oriented programming in JavaScript.

function doStock() {    //my class
var that = this;
var nAntiFreeze = null;   // timeout ID
var getContent = function(oInPageContainer) {  
    GM_log('Antifreeze, before clear ' +nAntiFreeze);
    //clearTimeout(nAntiFreeze);
    GM_log('Antifreeze, after clear ' +nAntiFreeze);
};

return {
    sLink : "",
    oList : "",
    sSplitOperator : ";",
    reset : function() {
        this.sLink = '';
        this.oList = '';
        this.sSplitOperator = ';';
        nAntiFreeze = null;
    },
    loadPage : function() {
        if (this.sLink.length == 0) return;
        if (this.oList.length == 0) return;
        nAntiFreeze = setTimeout(function(){GM_log(that); that.loadPage();},30000);
        GM_log('antifreeze ' + nAntiFreeze);
        getPageAsync2(this.sLink,false,getContent);  //GM_xmlhttprequest
    }
}

};

My script operates on GreaseMonkey in Firefox 4. Within my code, I utilize the above function/class to create an object like so:

var oStocker = new doStock();
oStocker.sLink = 'www.somepage.com';
oStocker.oList = 'some list, possibly a string line or an array object';
oStocker.loadPage();

The getPageAsync2 function invokes GM_xmlhttprequest and then delivers the result page contents within a div container to the callback function.

Initially, a general query arises: why does the value of nAntiFreeze not revert to null or any other value after calling the clearTimeOut function?

Secondly, why do I encounter the error

that.loadPage() is not a function
when the timeout expires? GM_log(that) shows me [object Object].

A previous respondent managed to resolve their issue by utilizing var that = this. Why doesn't it work for me? Custom Object calling Methods with setTimeout loses scope

EDIT: Thirdly, what happens if I generate a million objects? Will the browser dispose of them once they're finished working? Considering this object utilizes asynchronous ajax calls, I can't simply do

var oStocker = new doStock();
oStocker.loadPage();
oStocker = null;

The line oStocker = null will be executed before my object even completes its tasks.

Thank you

Answer №1

Initially, the value of nAntiFreeze is a basic value coming from the setTimeout function. This value is then passed back to clearTimeout in order to identify which timeout needs to be cleared. When you call clearTimeout, it does not modify the value of nAntiFreeze.

Next, the reason why that.loadPage is undefined is because when doStock() is invoked, that refers to this. If doStock() is called as a constructor with new, it points to a new Object. However, since your function does not return this object (i.e., the constructor's this), the reference is incorrect.

When you execute oStocker.loadPage(), the this keyword within it points to the oStocker object. On the other hand, the function passed to setTimeout references that, which has a closure to the constructor's this.

To fix this issue, consider the following solution:

loadPage : function() {

    // Define that here
    var that = this;

    if (this.sLink.length == 0) return;
    if (this.oList.length == 0) return;

    // When called as oStocker.loadPage(), this (and that) refers to
    // the oStocker object.
    nAntiFreeze = setTimeout(function(){GM_log(that); that.loadPage();},30000);
    GM_log('antifreeze ' + nAntiFreeze);
    getPageAsync2(this.sLink,false,getContent);  //GM_xmlhttprequest
}

If a constructor does not return its this, utilizing Richard Cornford's module pattern and employing closures for inheritance could be more beneficial.

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

After performing a Vuex action on one Vue.js component, the update is not reflected on another Vue

I am facing an issue with a component that renders a booking table. When I update my store in another component, the table does not get updated even though the store and computed properties are updated. I suspect that the problem lies with the filter not b ...

The 'name' property of Axios and Vuex is not defined and cannot be read

When making a call to axios in my mounted function to retrieve profile data, I send the payload to the 'set_account' Vuex store upon success. To access this data, I utilize MapGetters (currentAccount) in computed properties. However, when tryin ...

HTML5 input placeholder adapts its size and position dynamically as data is being

During my interaction with the input fields on my bank's website, I noticed that the placeholder text undergoes a unique transformation. It shrinks in size and moves to the upper-left corner of the input field while I am entering information. Unlike t ...

Adjusting the Materui LinearProgressWithLabel progress value to reflect a custom value

Is it possible to update the progress value of Material UI's LinearProgressWithLabel component with a custom value instead of the default one? I am trying to achieve this by obtaining my desired value from the upload progress in the Axios.post method, ...

Is there a way to verify the custom form when the braintree PayPal checkout button is clicked?

I am seeking a solution to validate a custom PHP form when the Braintree PayPal checkout button is clicked. Currently, the form redirects to the PayPal screen if it is not properly filled out. My goal is to prevent the PayPal popup window from opening if ...

How can you check the status of a user in a Guild using Discord JS?

Is there a way to retrieve the online status of any user in a guild where the bot is present? Although I can currently access the online status of the message author, I would like to be able to retrieve the online status of any user by using the following ...

What is the best way to synchronize the scale of images with the tempo of a song?

I just started learning CSS, JS, and HTML and I have a question about scaling an image based on a song. Despite searching through YouTube and various forums, I still haven't found a solution. Any help would be greatly appreciated :) Here is the HTML ...

Tips for using multiple Angular directive modules in PprodWant to enhance your Pprod experience by

Currently, I am working on jhipster Release 0.7.0 and our jhipster app has multiple types of directive modules – one for the index page and another for common directives. However, when we run the app on Prod profile, an exception occurs: [31mPhantomJ ...

Send form data without reloading the page and connect it to a JavaScript script

I've designed a system that reveals values based on a specific input selection. Below is the main form where users can enter model numbers and press enter: <form> <input type="text" name="ModNum" id="ModelNumber" pattern="^PIV13RT[23]?$" ...

What impact does nesting components have on performance and rendering capabilities?

Although this question may appear simple on the surface, it delves into a deeper understanding of the fundamentals of react. This scenario arose during a project discussion with some coworkers: Let's consider a straightforward situation (as illustrat ...

What is the advantage of not importing related modules?

As a newcomer to React, please excuse any novice questions I may have. I am currently utilizing npx create-react-app to develop a React app, but I'm unsure of the inner workings: Q1-If I were to throw an error in a component like so: import React, { ...

Animate out Material UI element with zoom effect and then remove it from the

I'm currently working on a dynamic user interface that allows for adding and removing items dynamically. Each item has both an add and remove button, with a special animation effect using Zoom. While this works smoothly when adding new items, I encoun ...

Guide on removing query parameters post a redirect using NextJS

Is there a way in NextJS to redirect a URL like /page?foo=bar to /page/bar? I checked out the documentation at https://nextjs.org/docs/api-reference/next.config.js/redirects but couldn't find a solution. This is what I have tried so far: { source: ...

Ensure that an HTML table row remains fixed on the screen at all times

I'm looking to make a specific row in my HTML table always visible on the screen, either at the bottom if scrolled off or top. The row should scroll normally as part of the table when it's visible on the screen. How can I accomplish this using bo ...

Guide to uploading a PDF to Google Drive and embedding it on an HTML static website

I manage a static HTML site for a small food shop. They require monthly menu uploads in PDF format. I believe uploading to Google Drive would be a more efficient solution than creating a separate admin view for file uploads. Can anyone advise me on how to ...

The operation of 'val' is not supported by HTMLInputElement

While working with a table row, I am iterating through each cell. Inside every cell lies a text box containing some value that I need to store in an array. function dothing() { var tds = $('#'+selected+' td'); var submi ...

"Embedding a Highcharts web chart within a pop-up modal window

I am looking to incorporate a Highcharts web chart onto a specific part of a Bootstrap modal, while ensuring the size remains dynamic along with the modal itself. Here's what I have attempted so far: Sample HTML code: <td><a href="#">${ ...

Tracking a razor ajax form using pace.js has never been easier with these simple steps

I'm currently exploring the use of pace.js with my Razor ajax form. The form generates a Partial View upon submission. Pace.js, as per its documentation, automatically monitors all ajax requests lasting longer than 500ms without any additional configu ...

Automatically update and reload Express.js routes without the need to manually restart the server

I experimented with using express-livereload, but I found that it only reloaded view files. Do you think I should explore other tools, or is there a way to configure express-livereload to monitor my index.js file which hosts the server? I've come ac ...

Using jQuery to alter hover color using a dynamic color picker

I'm looking to update the hover color using a color picker tool. Here are the methods I've attempted: // Initial Attempt $("input[type=color]").change(function(e) { var selectedColor = e.target.value; // $("body").css("background-color ...