Does Javascript move beyond the for loop and then return to it?

Currently, I am working on creating a stopwatch in JavaScript that counts by milliseconds using setTimeout. However, I encountered an issue during the initial setup:

var time = 0;

function main() {
  for (var i = 0; i < 5; i++) {
    setTimeout(timer, 1);
  }
  alert(time + " after the loop");
}

function timer() {
  time++;
  alert(time + " inside the loop");
}

document.getElementById("go").onclick = main;
#go {
    height: 40px;
    border: 1px solid lime;
    border-radius: 10px;
    background-color: lime;
}
<button id="go">Start!</button>

It seems like this piece of code is skipping over the for loop to the alert and then going back to the for loop. Can anyone explain what's happening here? My past experience with Python tells me that if you call a function within another function, the called function gets executed before moving to the next line of code in the main function. Does JavaScript operate similarly? Excuse my messy code, as I am still learning HTML/CSS/JavaScript.

Answer №1

When using setTimeout(timer, 1), the function timer will be executed asynchronously after the specified time delay (in this case, 1ms).

It's important to note that the code continues to run without waiting for the timeout to complete. This asynchronous behavior is non-blocking, which is why the "after the loop" alert appears before the others.

Answer №2

The reason for this behavior lies in the asynchronous nature of the setTimeout function.

Imagine the setTimeout function as taking a little journey to another realm (like calling a web api) to patiently wait for one second. This allows the code

alert(time + " after the for loop");
to execute first, before the timer function is eventually triggered by the event loop.

Answer №3

setTimeout() is a powerful tool in JavaScript, allowing you to execute a function after a specified amount of time. It operates asynchronously, meaning it does not pause the program's execution like a sleep statement would.

To make practical use of setTimeout(), consider using a closure function like so:

setTimeout(function() { console.log('Hello, world!'); }, 2000);

Keep in mind that the timeout value is in milliseconds, so be cautious when setting short intervals like 1.

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

Exporting a variable that is currently in use within a function being exported

I am currently working on setting up my mongodb in a separate file. I have created an initialization function where I write all the necessary code for connecting to the database and exporting the function. However, I also need to export the 'db' ...

"Efficiently Browsing Through Various Links with the Help of Greasemon

My goal is to open approximately 25 hyperlinks from a single page. All of these hyperlinks include the text Free Win. I am looking for a solution that will open each individual link in a new tab within the browser. I have written a Greasemonkey script, ...

``I'm having trouble with TablePagination styling on a material-table component. Anyone have

I am trying to customize the appearance of rows numbered from-to of x on a Material-Table, using the following code: import MaterialTable from 'material-table' import { TablePagination, withStyles } from '@material-ui/core' const Style ...

Creating Pinia stores as classes

I am looking to streamline my code by creating a "Class" that can easily generate multiple identical Pinia stores with specific data for each. How can I achieve this efficiently? import { ref } from 'vue' import { defineStore } from 'pinia&a ...

Using npm scripts in JavaScript: A comprehensive guide

Could someone provide me with a comprehensive guide or reliable reference material on how to execute running module commands within a JavaScript file? For example, I frequently use the following command: $ npm run webpack-dev-server --progress --colors - ...

A guide to utilizing Forwarding References in react-router-dom

I have a good grasp on Forwarding Refs and react-router-dom, but I'm struggling with the implementation in this particular scenario. The issue lies in trying to correctly use a function in a child component that sets null in a useState hook. I want th ...

What is the best way to retrieve the previously chosen item from an array?

I have successfully implemented dynamic pill tabs with one minor issue remaining. The most crucial aspect is that when I remove a pill, I want it to return to the previously opened tab. I have provided a StackBlitz example without routes on this page: -> ...

Transforming BufferGeometry to Geometry using FBXLoader within the Three.js library

Check out my snippet below for loading a .fbx object. It defaults to loading an object as BufferGeometry: const loader = new THREE.FBXLoader(); async function loadFiles(scene, props) { const { files, path, childName, fn } = props; if (index > fi ...

developing a segment within an HTML document

Recently, I came across a fascinating website at . I was particularly intrigued by the way the right and left columns expand and contract dynamically when clicked. As someone new to web development, especially in terms of dynamic websites using jQuery, I ...

Black-colored backdrop for Mui modal

Currently working with a mui modal and encountering an issue where the backdrop appears as solid black, despite setting it to be transparent. I attempted to adjust the color to transparent, but the issue persists. ...

Utilize AngularJS to Capitalize the First Letter and the Letter Following a Dot (.)

I am seeking a solution to capitalize the first letter in a given string, like so: sumo => Sumo Additionally, I need to capitalize strings in the following format: Dr.ravi kumar => Dr.Ravi kumar Although I have implemented an Angular filter that ...

I am facing an issue where PHP is failing to detect the '<del>' tag in my index.view.php file, resulting in it being omitted from the generated HTML

I've been working on updating my PHP code in the index.view.php file to display a strike through the task description if completed is set to true. I came across a Laracasts tutorial on classes where the instructor used <strike></strike>, w ...

navigate to the subsequent array element by clicking in JavaScript

My apologies if my explanation is unclear or if the code seems complicated, I'm still in the learning process. I am attempting to showcase data that is stored in an array. The objective is to have this data displayed upon clicking a button and then sh ...

Media queries in CSS not functioning as intended

Trying to scale media requests with an image (logo) for various mobile devices like iPhone 5, 6, 6+, iPads, and large screens. Need to specify styles for portrait and landscape orientation as well. The code seems to be functioning only for iPhone 6, iPads ...

Navigating in React Navigation: Techniques to Directly Access a Specific Index in a Datasource

I am a beginner at React Native and I have been working on developing a simple recipe app. Everything was going well until I reached the point where I needed to navigate to a specific recipe from my dataset. I am looking to create a singleRecipe.js compone ...

Extracting data from a dropdown menu and displaying it

I've created a form with a select tag that pulls options from a .csv file. However, I'm struggling to retrieve the selected option and display it later in the form. The variable to hold the selected currency is named $selectedCurrency. UPDATE: ...

Utilizing Angular's DSCacheFactory in my Ionic App: A Guide

Can someone guide me on implementing DSCacheFactory in my Ionic/Cordova app? I am unsure about using this and its similarity to web cache. Your help in finding a solution is greatly appreciated. Thank you! ...

Tips for decoding Dropbox Public folder images in HTML

Is there a way to read and display all images from a Dropbox public folder using jQuery loop? I have successfully displayed a single image like this: Simple Image "" But how can I access all images in the Dropbox public folder if their number is unknown ...

Tips for utilizing playFromPositionAsync method with expo-av Video in React Native

While working with the Video Expo component, I came across a prop called playFromPositionAsync. In the Video.d.ts file, it is defined like this: export default class Video extends React.Component<VideoProps, VideoState> implements Playback { ... ...

The replace() function is failing to replace the provided inputs

Supposedly, when a user types in certain profanity and submits it, the word is supposed to be replaced with a censored version. Unfortunately, this feature is not working as expected. The word appears uncensored. Do you think implementing if/else stateme ...