What causes my JavaScript setTimeout operation to resemble a setInterval?

For an exercise, I created a simple function to display a "binary clock" that updates every two seconds instead of one. This function is actually a modified version of similar code that works within an HTML form (updating a value repeatedly).

Below is my JavaScript-only modification:

function binaryClock() {                        
    let currentTime = new Date();
    let hr = currentTime.getHours();
    let mn = currentTime.getMinutes();
    let sc = currentTime.getSeconds();

    setTimeout('binaryClock()', 2000);
    document.body.innerHTML = '';
    document.write(hr + ':' + mn + ':' + sc + ' '); 
}

binaryClock();

Why does it operate in intervals like a regular clock where setTimeout essentially acts as setInterval with the binaryClock callback?

I find it intriguing that using setInterval() yields the same outcome, and as a beginner, I lack the necessary knowledge to explain why setTimeout(), typically executed once, mimics setInterval() behavior in this scenario. This discrepancy has piqued my interest enough to inquire about it here since I have not encountered such variance in my learning.

Answer №1

"How come my JavaScript setTimeout acts as a setInterval?"

This is happening because you have designed it like that. Your function binaryClock() is being called recursively.

Answer №2

Similar to setInterval, the function setTimeout(binaryClick, 2000) is called on every tick.

In essence, with each "tick" of your clock, it triggers the following tick.

Answer №3

Big shoutout to deceze for pointing out my oversight in the original code regarding recursion. It has come to my attention that the function actually calls itself each time it is executed, thanks to the call inside setTimeout() or setInterval:

Even though only 2 seconds are accounted for in each iteration, the function will continue to recursively call itself due to the nature of how the language is typically interpreted.

Ultimately, this recursive behavior essentially mimics the functionality of a setInterval().

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

The execution of the HTTP request is not happening

As a newcomer to JS and Node, I am attempting to display a JADE view using JSON obtained from a REST API. Everything works perfectly when I run the http.request on its own, but as soon as I introduce modules and rendering statements, the http request funct ...

Launching a Node.js script with pm2 and implementing a delay

Utilizing the amazing pm2 package to maintain the longevity of my node.js applications has been extremely helpful. However, I have encountered a problem that I am unsure how to resolve. One of my applications involves multiple scripts, a server, and sever ...

Ways to Conceal <div> Tag

I need help with a prank .html page I'm creating for a friend. The idea is that when the user clicks a button, a surprise phrase pops up. I have managed to hide and unhide the phrase successfully using JavaScript. However, my issue is that when the pa ...

The React component fails to render on a Razor page

Looking to render a React component within a Razor page but without using a div? You can achieve this by utilizing ReactDOM.render, however my goal is to utilize it as a tag within the Razor page itself. For example, if I have a class named App, I would li ...

Creating a workaround for mapping legacy URL fragments to element names in Backbone.js

Is there a workaround for linking to specific parts of a page in a backbonejs application? I have found solutions for static HTML pages by using the `name` attribute and `#fragment` in the URL, but this approach doesn't seem to work directly in backbo ...

Error: The object does not have the property createContext necessary to call React.createContext

I'm currently exploring the new React Context API in my app. I've also implemented flow for type checking. However, when I add // @flow to a file that contains the code: const MyContext = React.createContext() An error pops up stating: Cannot ...

The Error message "Property 'data' is not present in Type <void> | AxiosHttpResponse<any>" is indicating that the data property is missing on

When I fetch data for a specific user, I have a promise that I use to setState. Below is the implementation: getUserUsername = (): string => { const { match } = this.props; return match.params.username; }; onFetchUser = () => getUse ...

Enhance Form within React Calendar

I have developed a calendar using React and Redux. When I click on an empty date, a modal pops up allowing me to add an event. However, I am struggling to implement the functionality to edit that event by clicking on it later. Can someone guide me on the c ...

Problem with jQuery's UI autocomplete functionality

Implementing jQ UI Autocomplete with multiple values Below is how my function is structured: mailto_input.bind( "keydown", function( event ) { if ( event.keyCode === $.ui.keyCode.TAB && $( this ).data( "autocomplete" ).menu.active ) { ...

What exactly is HTML cloud storage all about?

As I work on developing an app through phonegap, one question that comes to mind is the possibility of storing information online. For instance, if there's a number variable that increases when a button is pressed, can this value be saved somewhere an ...

What is the best way to send multiple XMLHttpRequests for JSON data from various sources?

I am attempting to make multiple XMLHttpRequests in JavaScript with two different URLs. My goal is to store each response in a variable and manipulate them all collectively. Currently, this is how I am doing it. Is there a more graceful approach? var fir ...

Using canvas transformation changes the way drawImage is applied

I have been working on a game as a hobby and you can find it at . I have managed to get most aspects of the game working well, such as transformation, selection, movement, and objects. However, there is one particular challenge that I am struggling with. ...

The switch statement is not yielding any results

I am currently working on a test that involves processing a string through a switch statement. However, I am facing an issue where the integer value set in the case of the switch statement is not being passed correctly. As a result, the subsequent if state ...

The authentication method "discord" is not recognized

Currently, I am working on implementing discord authentication using passport. Originally, everything was functioning correctly, but now it seems to have encountered an issue which I cannot identify. auth.js const express = require('express') co ...

Building a Multiple Choice Text Box with HTML

I am looking to create a section on my website where I can display text, and I have 9 buttons on the page that I want to stay within the same page without redirecting. The goal is for the text to update based on which button is clicked, with a fading ani ...

nodejs callbacks and their return values

Hey guys, I'm having trouble resolving an issue with a JavaScript callback return. Here's the function in question: //Function to get user's contact list function get_contact_list(data) { //Retrieve user ID based on ...

Tips for iterating through an associative array/object within a MongoDB schema instantiation using mongoose without the need to specify schema configuration parameters

I've been searching on Google for hours without finding a clear answer. Perhaps I need to adjust my search terms? Here's my question: I'm a beginner with MongoDB and I'm trying to modify the values of a schema instance before saving it ...

Designed radio buttons failing to activate when focused using a keyboard

I'm facing an issue with radio input buttons that I've dynamically added to a div using jQuery. They function properly when clicked with a mouse, but do not get activated when using the keyboard tab-focus state. NOTE: To style the radio buttons ...

Encountered a problem while trying to install using npm install

Encountering an error while running npm install on Ubuntu 12.04: Here is a snippet from my npm-debug.log showing where the errors occur: ... (contents of npm-debug.log) ... This is my package.json: { "name": "www", "version": "0.0.1", /"p ...

Using AngularJS to populate dropdown options with data from JSON objects

I have a JSON file that looks like this: var myJson = { "Number of Devices":2, "Block Devices":{ "bdev0":{ "Backend_Device_Path":"/dev/ram1", "Capacity":"16777216", "Bytes_Written":9848, "timestamp":"4365093 ...