How come repeatedly using window.setTimeout for the same function does not create an endless loop?

I recently came across this code snippet:

class CentralControlUnit {
    private devices: Device[] = [];
    constructor() {
        // Adding a new device MobileDevice
        this.devices.push(new MobileDevice(this));
    }

    activate() {
        for (var i= 0; i < this.devices.length; i++) {
            // Activating the device
            this.devices[i].switchOn();
        }
        window.setTimeout(() => this.activate(), 1000);
    }

    triggerAlarm(alertMessage: string) {
        console.log('Alert! ' + alertMessage);
    }
}

var ccu = new CentralControlUnit();
ccu.activate();

I'm curious why

window.setTimeout(() => this.activate(), 1000);
doesn't create an infinite loop.

From what I understand, ccu.activate() iterates through each device in devices first and then schedules another call to activate using window.setTimeout, which repeats every 1 second.

Check out Listing 3-3. Delegation in Pro TypeScript: Application-Scale JavaScript Development for more details.

Answer №1

Put simply, there is no risk of creating an infinite loop when using setTimeout since it does not block the code execution. Instead, the function provided to execute, () => this.start(), is queued up and executed after a one-second delay. The start method finishes executing after calling window.setTimeout, preventing an actual infinite loop from occurring in the traditional sense. Typically, the code will remain in a state of waiting until the next timer event.

While it is true that the code continually schedules a timer to call the start method, it does not result in an infinite loop as control is returned to the javascript runtime each time.

Answer №2

Implementing a delayed 1-second infinite loop

window.setTimeout(() => this.start(), 1000);

can be likened to

var _this = this; 
window.setTimeout(function(){ _this.start(); }, 1000);

This is known as an Arrow Function

Answer №3

If you're looking for a solution, consider utilizing the setInterval method. This can create an indefinite loop that is easily terminated using clearInterval.

this.interval = window.setInterval(() => {
...
}, 5000);

window.clearInterval(this.interval);

Another option is to utilize:

this.sensors.forEach(sensor => sensor.check())

This approach eliminates the need for a traditional for loop.

Answer №4

A common mistake is trying to use setTimeout within a class, where "this" refers to the setTimeout function itself instead of the intended class. To remedy this issue, consider the following code:

class CentralControlUnit {
    private sensors: Sensor[] = [];
    
    constructor() {
        // Add instances of various sensors
        this.sensors.push(new HeatSensor(this));
    }
    
    start() {
        let self = this; // Store reference to current instance
        
        for (let i= 0; i < this.sensors.length; i++) {
            // Invoke sensor check method
            this.sensors[i].check();
        }

        window.setTimeout(() => self.start(), 1000); // Call start method every 1 second
    }

    activateAlarm(message: string) {
        console.log('Alarm Triggered - ' + message);
    }
}

let controlPanel = new CentralControlUnit();
controlPanel.start();

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

Selecting Content Dynamically with jQuery

I have a webpage with multiple dynamic content sections. <div id="content-1"> <div id="subcontent-1"></div> <i id="delete-1"></i> </div> . . . <div id="content-10"> <div id="subcontent-10"></d ...

The type 'BusinessParameter[]' does not share any properties with the specified type

Within my API function, the return type is specified as Promise<BusinessParameter[]> because the expected outcome is an array of BusinessParameters. Despite assigning the same type to the variable where this result is stored (returnOrderItemBusinessP ...

Error Code 1: Cordova FileTransfer Writing Issue

In my Android application using Cordova 4.2.0, I am experiencing challenges with getting the FileTransfer plugin to function correctly. It seems like there might be an error in the code. exception:".myApp\/contentImages\/20150110220101.jpg: open ...

Navbar Growth Effect

I'm attempting to create an expanding effect in my navbar using Angular. When I click on "show information," the content should slide up. The issue is that the top part of my footer does not follow the effect. I have tried something like: <foot ...

JS: Submitting form data through POST method but fetching it with GET method?

When using PHP to retrieve data, the $_POST method cannot be used; only $_GET. Why is that? Could it be that I am not sending my form data correctly? I assumed that by using request.open("POST"), the form would be processed as a POST request rather than a ...

What could be the reason for the malfunction of this angular binding?

Looking at the HTML below: <input type="checkbox" name="person" [(ngModel)]="person.selected" /> This input is part of a ngFor loop. Testing has revealed that despite some values of selected being true and others false, all checkboxes appear check ...

Using JavaScript to dynamically hide an ASP ComboBox based on the selected value in another ASP ComboBox in an ASP.NET application

I am facing an issue with two asp comboboxes. One is named cmb_stocktype, and the other is named cmb_tagno. My requirement is that when I select cmb_stocktype with the value of WithStock, then cmb_tagno should be displayed; otherwise, it should be hidden u ...

"Regardless of the circumstances, the ionic/angular service.subscribe event

Currently, while developing the login section of my Ionic app, I am encountering an issue with the getTokenAsObservable.subscribe() function. The main problem is that the function checks the token status when it is saved (by clicking the Login button) or ...

The TypeError encountered when using vue.js push arises from attempting to access the 'name' property of an undefined value

Here is a code snippet I am working with: new Vue({ el: '#core', data: { checkedThemes: [] ... } }) Afterwards, I have the following code: mounted() { ... var theme = parseInt(parameters['theme&apo ...

What steps should I take to address conflicting type identifiers between Cypress and jQuery?

Currently, I am tasked with writing TypeScript end-to-end tests for an Angular 11 application. Following the recommended practices of Cypress, my test setup is encountering a conflict due to existing jQuery dependencies (3.5.1) in the app and Cypress (8.4. ...

What is the significance of the 'this' context type void not being assignable to type rule?

Currently, I am conducting tests using Typescript to explore the feasibility of a project I have in mind. In one of my functions, I need to specify the type of 'this' as a class. While it technically works, I continue to encounter an error messag ...

Delay in Angular 2 Change Detection when using Arrays and @Inputs is experienced for a few seconds

Trying to wrap my head around change detection in Angular 2 has been a bit challenging with the plethora of information available. I've been working with "buckets" fetched from Firebase, pushing them into an array, and passing that array into a child ...

Silence and Restore background noise

In the monitoring page of my website, I have implemented an alert sound that plays based on certain conditions. The code for playing the alert is as follows: $('body').append('<embed src="'+alerts+'" id="beapImg" autostart= ...

Employing promises for fetching data via XHR results in a promise that is still pending

Currently, I am experimenting with promises to handle asynchronous requests using XHR. Interestingly, I noticed that when I try to log the result within the .then function, it works perfectly fine. However, if I attempt to log it outside of this scope, it ...

I am attempting to gather user input for an array while also ensuring that duplicate values are being checked

Can someone assist me with the following issue: https://stackblitz.com/edit/duplicates-aas5zs?file=app%2Fapp.component.ts,app%2Fapp.component.html I am having trouble finding duplicate values and displaying them below. Any guidance would be appreciated. I ...

enhancing a node-express-browserify project with jadeify

Unique Context I recently set up a project based on a node-browserify boilerplate example. My development environment is using coffee-script. Currently, I am attempting to integrate jadeify into the setup with the following code: bundle = browserify ...

Problem with deploying a Nextjs project on cPanel

I've been struggling to deploy a nextjs project on cPanel. The project consists of only one SSG page. I set the basePath in next.config.js to deploy the project, but I keep getting a 404 page not found error and the page keeps getting called in the ne ...

Tips for implementing vue-multiselect tagging within an ASP.NET solution in Visual Studio 2017

I am attempting to implement vue-multiselect tagging, but encountering some errors such as: "vue.js:634 [Vue warn]: Unknown custom element: - have you registered the component correctly? For recursive components, ensure that the "name" option is provided ...

The pop-up window created programmatically refuses to close

I am struggling with an issue where I am opening a pop-up from the code behind as a waiting image while processing some background activities. However, the pop-up does not close after the activity is done. Can someone please help me figure out what I am ...

What is the process for accessing the gallery in phonegap on an android device?

Hey there! I'm new to phonegap and I'm trying to figure out how to access the gallery using Javascript. Unfortunately, I haven't been able to find any helpful articles on this topic. Can someone please guide me through the process? While wa ...