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:

     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)
         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; }



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.

Recommended Answers

All 3 Replies

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!

yea yea i figured it out by now but tnx for the further explanation!

Member Avatar

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.

commented: tcp +0
commented: tested +0
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.