0

I m new to javascript and I m little bit confused on how does a webpage read the actual script.
let's say I have the folowing code:
<script>

     vrijeme = document.getElementById("Label7").innerText;
     minute = vrijeme.substring(0, 2);
     sekunde = vrijeme.substring(3, vrijeme.length);
     alert("fuck you");

     var start_time=setInterval(secondFunction, 1000);

     function secondFunction()
     {
         sekunde = sekunde - 1;
         if (sekunde < 0)
         {
             minute = minute - 1;
             sekunde = 59;

         }
         if (minute <0)
         {
             clearInterval(start_time);
         }
         if (sekunde < 10) { document.getElementById("Label7").innerText = minute + ":0" + sekunde; }
         else { document.getElementById("Label7").innerText = minute + ":" + sekunde; }

         if (minute < 10 && minute < parseInt(vrijeme.substring(0,2))) { document.getElementById("Label7").innerText = "0"+minute + ":" + sekunde; }


     }

  </script>

and I add the function to my button onclick event ...
I noticed that as soon as I opened the browser the SCRIPT RAN! So i suppose the script runs automatically as the webpage opens?
The other question that is bothering is related to the above code. The setInterval function reffers to the actual function that is written. How does the browser see the public variables declared in the script since the setInterval() function just points to the written function but not the code that is above the function (the variables ect...). I hope I was clear enough.
It would be great if you can recommend an article about .js execution on a web page.

3
Contributors
3
Replies
25
Views
3 Years
Discussion Span
Last Post by [NOPE]FOREVER
1

JavaScript is executed as the browser encounters it within your HTML document. So freestanding code is executed immediately, but functions are executed only when called. This has significant implications for your scripts. For example, if the code you posted was in the <head> section of your document, it would fail because the content of the document body doesn't "exist" yet so, similarly, the element with the id of "Label7" doesn't exist. But if you moved the code to the end of your doucment, or enclosed it in a function that was called by the 'onload' event, it would work as you expect.

As far as "public variables" are concerned, I'd suggest you do a search on "JavaScript variable scope". Good luck!

6

js is invoked when the web page loads, the functions are executed when an event happens such as clicking a button. functions may also be executed when the page loads itself for example an event listner that executes a particular function or number of functions onload with requires paramaters.

Votes + Comments
tested
tcp
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.