What causes the setTimeout function to run indefinitely?

I recently came across a timing event and have some doubts regarding the usage of setTimeout. I found an example on W3Schools where it is set to run every 500 milliseconds. However, my understanding is that setTimeout functions only once. You can view the example on W3Schools through this link.

<head>
  <script>
    function startTime() {
      var today=new Date();
      var h=today.getHours();
      var m=today.getMinutes();
      var s=today.getSeconds();
      document.getElementById('txt').innerHTML=h+":"+m+":"+s;
      setTimeout(function(){startTime()},500);
    }
  </script>
</head>
<body onload="startTime()">
  <div id="txt"></div>
</body>

Answer №1

Inside the function, the timer is reset:

setTimeout(function(){startTime()},500);

Each time this function executes, it always ends by scheduling a new iteration.

Answer №2

The setTimeout function is designed to execute only once. Take a closer look at your code. In the startTime function, you have set it up to call itself again after 500 ms. If you need it to run just once, avoid recursive calls. But if you intend for it to be repeated for a duration, consider using setInterval instead. This alternative function provides an identifier that can be used to halt its execution at any time.

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

Retrieve complete browsing history using asp.net

Similar Question: How can browser history be accessed? I am interested in obtaining a list of websites visited by the client through their browser history in order to gather information from these sites and display it on my website. How can I access t ...

How can one generate a custom link using vue-router in Vue.js after the rendering process has been completed?

Currently, I am utilizing VUE and I must say, boostrap-table is performing admirably! Within my component, I have the following: <BootstrapTable :columns="table.columns" :data="table.data" :options="table.options"></ ...

New project was successfully generated, but the information is missing when transmitted from React to Django API

I recently developed a React + Django application and implemented a basic CRUD feature. Everything was working smoothly until I encountered an issue while creating a project and storing it in the Django database. When I view the project at projects/list, o ...

Guide to encapsulating an asynchronous function in a promise

I am in need of wrapping an asynchronous function within a promise to ensure synchronous execution. The reason behind this is that I must obtain a result from the asynchronous function before proceeding with the program's execution. Below is the rele ...

What could be causing the malfunction in this multi-select code developed by loudev?

I tried adding this link: After following the instructions, the code is still not functioning correctly. I made sure to include jQuery scripts as well because I thought they might be necessary. I'm having trouble identifying where the mistake lies. ...

Node.js encountering issue with printing an array

Here is the code snippet from my routes file: router.get('/chkjson', function(req, res, next) { req.getConnection(function(err,connection){ var ItemArray = []; var myset = []; var query = connection.query('SELEC ...

Triggering JavaScript Function When Scrolling in Overflowed DIV

After using jQuery and searching for various ways to make this script work, I finally found a solution that works for my index.html file. <div style="overflow-y:scroll; height:300px"> <div style="background-color:black; height:500px"> </div ...

javascript utilizing the canvas feature to resize and add graphics to an image

Is it possible to leverage Canvas for drawing over images that have been downloaded by users, all while adjusting the scale? For instance: User uploads an image Starts drawing on the image Zooms out and continues adding more drawings All modifications ...

To effectively delete the <li> element using JavaScript, make sure to eliminate the associated array object as well

I am in the process of designing a compact landing page that will randomly select a city from user input to determine the next trip destination. When the user types in the city name into the input field, everything functions correctly - a new list element ...

PHP script to refresh a div when a file is changed

I am working with a Raspberry Pi that is connected to buttons, allowing me to change the value in a file named "setting.txt". The contents of this file may be as simple as: 42 The buttons trigger a process that updates this file (for example, changing 42 ...

Discovering the attribute of a DOM element (or, to be more precise, the class of a div)

Here's the code snippet I'm working on: <body class="asdf"> <span>hey! <div class='hideContent'>test</div> the ultimate experience</span> <span id="blarg">original</span> </b ...

When using Node.js, the process.exit() function will not terminate if there is an open createReadStream

My program interacts with Asterisk using EAGI, where Asterisk communicates with my Node.js application by sending data via STDIN and receiving commands via STDOUT. When a user ends the call, the Node.js process receives a SIGHUP signal for clean terminatio ...

What is the best way to include the title "addmoves" to the server using AngularJS?

https://i.sstatic.net/yR2fk.png Furthermore, I am looking to include a button that allows users to add additional movies. The goal is to input multiple sets of data simultaneously, such as: newMovies = [ { movieName:"", director:"", release ...

Change the syntax to use async-await

Is it worth converting the syntax to async-await and how can I achieve this? // ---- UserRoutes ---- router.get('/user', middlewareJwt.jwtHandler, function (req, res) { UserService.get(req.userId, (user) => successCbk(res, 200, { ...

Sending information to components in Angular using Router

Should I pass data through the angular router to a component, or is it better to use a service? Currently, the component is receiving data in the following way: this.account = activatedRoute.snapshot.data.account ...

Is it possible to retrieve the HttpsError status from a Firebase function?

Within my firebase function, I deliberately throw an error with a specific status and message using the following code: throw new functions.https.HttpsError('permission-denied', 'Token does not match'); When I receive the server respo ...

What is the best way to maintain an ongoing sum of multiple values using bacon.js?

Experimenting with the power of bacon.js. I want to maintain a dynamic total of values from a set of text inputs. The example on the github page utilizes the .scan method along with an adding function, which functions well for simple increment and decremen ...

The validation function for email addresses in Express-validator seems to be malfunctioning

I've encountered an issue with the validation process in my code. Everything seems to be working fine except for the .isEmail method, which keeps flagging even valid email addresses as invalid. No matter how I adjust the validation rules, the problem ...

Eliminate the dropdown menu from an HTML table

I have a table with dropdown lists in each row's second column. How can I remove a dropdown list from a row if the value in that row is "Delivery"? Check out my fiddle here: https://jsfiddle.net/fp67wLqz/ window.onload = $('#my_id tbody tr&apo ...

JavaScript WYSIWYG Algorithm

Despite my searches on SO, it appears that most questions revolve around simply making a div editable using contenteditable="true". I am interested in finding the most effective method for tracking all formatting tags applied to a document. Merely togglin ...