简体   繁体   English

为什么我不需要在脚本标签中设置 onload 事件来运行 setInterval() 方法?

[英]Why i do not need to set onload event to run setInterval() method in the script tag?

Hello I am new in Javascript i want to know that this code is changing image every four seconds and it is working very well but i did not give onload event here to run setInterval() method but still setInterval() got called how?您好,我是 Javascript 的新手,我想知道此代码每四秒更改一次图像,并且运行良好,但我没有在此处提供 onload 事件来运行 setInterval() 方法,但仍然调用 setInterval() 如何? who called setInterval() method?谁调用了 setInterval() 方法?

<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>

Code in <script> elements is ran automatically when the script tag is received. <script>元素中的代码在收到脚本标记时自动运行。 To wait until the page finishes loading, you do <script defer> .要等到页面完成加载,请执行<script defer>

For example,例如,

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

This would print Hello World!这将打印Hello World! to the console immediately when the <script> tag is received.收到<script>标签后立即发送到控制台。

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

This would print Hello World!这将打印Hello World! to the console after the page finishes loading.页面加载完成后到控制台。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM