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

Show the form when the button is clicked

I want to create an application that allows users to click on a button in the top right corner (check image) to hide one div (topics) and show another div (a form for adding a new topic). Here is what it looks like: https://i.stack.imgur.com/YeRTw.png ...

combine the value of one key with the value of another key within an array

const array = [{ id: 1, name: 'Bob', education: [{ degree: 'bachelors', Major: 'computers' }, { degree: 'masters', Major: 'computers' }] }, { id: 2, n ...

The comparison between using multiple Vue.js instances and components, and implementing Ajax tabs

I am looking to incorporate ajax tabs using vue js. Each tab will need an ajax request to fetch both the template and data from an api. Here is an example of the tabs: <div id="tabs"> <ul class="nav nav-tabs"> <li class="active">& ...

Methods for submitting POST requests with key data enclosed in quotation marks?

Upon investigation, I discovered that the Request Payload object's key does not have quotation marks as shown below. However, I am interested in sending a request with keys that are marked with quotations. Interestingly, when I attempted to send a re ...

If the checkbox is selected, the textbox will receive the class "form-input validate required" upon Jquery validation

I am using Jquery Validation plugin to validate a form on my website. Below is the HTML form code: <form id="caller"> <label>Phone:</label> <input type="text" name="phone" id="phonen" class="form-input" value="" /> <di ...

Tips on submitting JSON data to a server

I need the data to be structured like this {"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7f0c3f18121e1613511c1012">[email protected]</a>","password":"1"} but it is currently appearing like this { & ...

Get the large data file in sections

I ran a test script that looks like this: async function testDownload() { try{ var urls = ['https://localhost:54373/analyzer/test1','https://localhost:54373/analyzer/test2'] var fullFile = new Blob(); for (le ...

Trouble with Fetching JSON Data using AJAX

Having trouble retrieving JSON data from an acronym finder API using a simple GET request. Here is the code I'm using: $.ajax('http://www.nactem.ac.uk/software/acromine/dictionary.py?sf=DOD', { crossDomain:true, dataType: "jsonp ...

Is it possible to efficiently update the innerHTML of multiple div elements using a single function?

Upon clicking a button, I am dynamically updating the content of multiple divs using innerHTML. Currently, the button triggers a new video source to load, but I also want to change other types of content in different divs at the same time. I wonder if cha ...

Are there any potential performance implications to passing an anonymous function as a prop?

Is it true that both anonymous functions and normal functions are recreated on every render? Since components are functions, is it necessary to recreate all functions every time they are called? And does using a normal function offer any performance improv ...

Tips for preserving input field data in an AngularJS scope variable

I am having trouble storing textbox values in my 'Values' variable. When I enter values in the textboxes, it seems to be getting the hard-coded values instead. Can someone please help me with this AngularJS issue as I am new to it? Here is the co ...

Vue should only activate the element that has been clicked on

I'm currently working on my first Vue project and encountering an issue with triggering a child component within a table cell. Whenever I double click a cell, the `updated` event is being triggered in all child components associated with the table cel ...

Vue form component triggers the submit event twice

In my current project, I am utilizing the most recent version of Vue 3 without any additional vendors. After experiencing a setback in which I invested several hours attempting to uncover why my form component was triggering the submit event twice, I am le ...

Conflicts arising between smoothState.js and other plugins

After successfully implementing the smoothState.js plugin on my website, I encountered an issue with another simple jQuery plugin. The plugin begins with: $(document).ready() Unfortunately, this plugin does not work unless I refresh the page. I have gone ...

Initiate Action Upon Visibility

After discovering this script that creates a counting effect for numbers, I realized it starts animating as soon as the page loads. While I appreciate its functionality, I would prefer it to only initiate when the element is in view; otherwise, the animati ...

What is the best way to load $cookies into an Angular service?

After defining an Angular service where I need to access a cookie, I noticed that the $cookieStore is deprecated and that it's recommended to use $cookies instead. This is how my service is set up: 'use strict'; var lunchrServices = angul ...

In React, facing difficulty in clearing setTimeout timer

After clicking the button, I want my code to execute 3 seconds later. However, I'm having trouble achieving this. It either runs immediately or doesn't stop running. <Button onClick={setTimeout(() => window.location.reload(false), 4000), cl ...

Error encountered: The JSONP request to https://admin.typeform.com/app/embed/ID?jsoncallback=? was unsuccessful

I encountered an issue with the following error message: Error: JSONP request to https://admin.typeform.com/app/embed/id?jsoncallback=? Failed while trying to integrate a typeform into my next.js application. To embed the form, I am utilizing the react-ty ...

Best method for creating HTML elements with jQuery

I've come across various styles and methods for creating elements in jQuery, each with its own unique approach. I am interested in discovering the most effective way to construct elements and whether a specific method stands out as superior for any pa ...

Undefined data is frequently encountered when working with Node.js, Express, and Mongoose

Having a beginner's issue: I'm attempting to use the "cover" property to delete a file associated with that collection, but the problem is that it keeps showing up as "undefined". Has anyone else encountered this problem before? Thank you in adv ...