Why don't I need to include an onload event to execute the setInterval() method within the script tag?

Hey there! I'm diving into the world of Javascript and I've come across this interesting code that changes an image every four seconds. Surprisingly, it's working perfectly fine even though I didn't include an onload event to execute the setInterval() method. How is it possible that setInterval() still got called without me explicitly calling it? Who could have triggered the setInterval() method?

<html lang="en">
<head>       
    <title>sliding image</title>
</head>
<body>
    <img id="img1" src="" alt="" width="1200px">
    <script>
       let images = [
           "C:\\Users\\SUDARSHAN\\Desktop\\html_UI\\images\\1200px-Heart_corazon.svg.png",
           "C:\\Users\\SUDARSHAN\\Desktop\\html_UI\\images\\alex-haney-AGqzy-Uj3s4-unsplash.jpg",
            "C:\\Users\\SUDARSHAN\\Desktop\\html_UI\\images\\mitchell-luo-jz4ca36oJ_M-unsplash.jpg"
        ];
        let i = 0;
        
        function image()
        {  
              let img2=document.getElementById("img1");
              i = (i + 1) % images.length;
              img2.src = images[i];
        }
       window.setInterval(image,4000);
        
    </script>
</body>
</html>

Answer №1

When a <script> element is included in the HTML, the code inside it will be automatically executed when the browser encounters it. To delay the execution until after the page has finished loading, you can use the <script defer> attribute.

For example,

<script>
  console.log("Hello World!")
</script>

In this case, "Hello World!" would be printed to the console as soon as the <script> tag is encountered by the browser.

<script defer>
  console.log("Hello World!")
</script>

With the <script defer> attribute, "Hello World!" will only be displayed in the console after the entire page has finished loading.

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

Is there potentially a memory leak in this code? If there is, what steps can be taken to eliminate it?

Recently I inherited a project from my senior colleagues that focused on seamless page reloading using AJAX. The code is filled with numerous functions like this one: function iCreateProblems() { //some random code document.getElement ...

Generate a random number to select a song file in Javascript: (Math.floor(Math.random() * songs) + 1) + '.mp3'

My current JavaScript code selects a random song from the assets/music folder and plays it: audio.src = path + 'assets/music/'+(Math.floor(Math.random() * songs) + 1)+'.mp3' However, I've noticed that sometimes the same trac ...

Navigating between two Vue2 applications

I currently have two applications, app1 and app2. App1 serves as a website at www.wxample.com with a button. My goal is to implement code in app2 that allows me to click the button on app1 and be redirected to the Login Panel in app2 for the workers module ...

Enhance the color scheme of your collapsed or expanded Bootstrap NAV for mobile devices

Currently working on customizing the navbar using Bootstrap. I've been able to style it perfectly for both desktop and mobile devices in its initial state. The issue arises when attempting to style the navbar in its expanded and collapsed states on m ...

JavaScript and Responsive Design Techniques

I'm struggling to create a responsive page that starts with a mobile-first approach, but I keep running into the same issue. When I have my dropdown menu in the mobile version, it looks good. However, when I try to switch it to the non-mobile version ...

Struggling with uploading files in AngularJS?

Below is the code snippet from my controller file where I aim to retrieve the values of various input elements (name, price, date, image) and store them in an array of objects... $scope.addBook = function(name, price, date, image) { name = $scope ...

Solving the Challenge of URL Issue in Ajax Call to MVC Controller

I have searched extensively for a solution to my jQuery/MVC problem, but haven't found one that works. Here is the JavaScript code I am using: $.ajax({ type: "POST", url: '@Url.Action("Search","Controller")& ...

Learn how to display JSON data sent from the server on a webpage

I'm just starting out with jquery. I have an api called '/categories' that gives me a json object of categories. The response looks like this: [ { name: "Laptop deals", slug: "laptop-deals", imageURL: "image.jpg", id: 1 }, { name: "Fashion ...

NextJS displays outcomes as per query parameters obtained from an external API

I have set up my NextJS app to connect to a rest API. The API returns results based on different filters in the query string, such as: /jobs /jobs?filter=completed /jobs?filter=upcoming /jobs?filter=cancelled On my NextJS page, I have a few buttons that I ...

Having trouble with Lerna bootstrap? You might be running into the dreaded npm error code E401

Every time I run Lerna bootstrap on Jenkins, it fails with an error, but it works fine on my local machine. npm ERR! code E401 npm ERR! Unable to authenticate, need: BASIC realm="Sonatype Nexus Repository Manager" Package.json in the main folder ...

Accessing Ionic rootScope within the config stateprovider - A step-by-step guide

Is it possible to access the value of $rootScope in the following line? .config(function($stateProvider, $urlRouterProvider) { $stateProvider // I am trying to retrieve the value of $rootScope here. } ...

The Webstorm AngularJS extension appears to be malfunctioning, as it is not able to recognize the keyword 'angular'

As a beginner in Angularjs and web development, I have been using Webstorm to develop my projects. I have already installed the Angularjs plugin, which seems to be working fine in my HTML files. However, I am facing an issue with my .js file. In this file, ...

The technique of accessing parent props from a child composition component in React

I am trying to reduce every letter prop from the child component, Palata. How can I achieve this? index.js <Block letter="I" mb={16}> <Palata letter="I" start={4} end={9}/> <Wall/> <Empty/> <Palata le ...

Extract information from a string to retrieve the array specifications

After making a request to the server, I received the following response: { "statusCode": 200, "body": "{\"Errors\":\"\",\"Message\":\"\",\"Output\":\"\",\"TokenID\":\"F10645774 ...

Click to remove the ellipsis from the backbone

Some Background Info I am working on creating a feed similar to Twitter where each row expands on click to show more information. The data is fetched from a JSON file sent from the backend to the frontend, and I am using Backbone.js for rendering. My fee ...

Adjust the size of the font in accordance with the value of the span text

I am looking to adjust the font size based on the value within the span element. The numbers in the class name may vary. Issue: using text() retrieves all values (e.g. 50020) I want to incorporate each() and $this in some way. How can I do this? Thank ...

Maintaining the consistent structure of build directories within a Docker container is crucial, especially when compiling TypeScript code that excludes the test

Our application is built using TypeScript and the source code resides in the /src directory. We have tests located in the /tests directory. When we compile the code locally using TSC, the compiled files are deposited into /dist/src and /dist/test respectiv ...

Is there a way to change the border property of an element when clicked, without causing the displacement of other elements?

I'm in the process of creating a webpage where users can choose the color and storage capacity of an item. Only one color/capacity can be selected at a time, and once chosen, it should be highlighted with a border. The issue I encountered is that whe ...

What is the method for incorporating parameters into an array filter?

Imagine having an array containing multiple duplicate objects. How can we create a condition to specifically identify objects with certain criteria, such as matching IDs, duplicate status, and duplicate dates? The goal is to only display the object with th ...

Element not chosen in Angular version 6

Recently delving into Angular 6, I've been working on setting up form validation within an Angular form. Validation has been successfully implemented, but there's a minor issue with the select box displaying an empty first value. Here is my code ...