Yes, I know that this is probably a very stupid question, but this has been bugging me for a while.
Ok, so I have been learning JavaScript for a while now and have understood everything perfectly. . .except for function "parameters" (I believe they are called).
I was taught that they work like so:
function test(number) {
document.write(number);
};
test(1);
test(12);
This makes perfect sense to me. However, recently, I've come across some that were a little different.
var counterDays = document.getElementById('days');
var counterHours = document.getElementById('hours');
var counterMinutes = document.getElementById('minutes');
var counterSeconds = document.getElementById('seconds');
var date = new Date('December 28, 2016 00:00:00');
function updateTimer(date) {
var time = date - new Date();
return {
'days': Math.floor(time / (1000 * 60 * 60 * 24)),
'hours': Math.floor((time/(1000 * 60 * 60)) % 24),
'minutes': Math.floor((time / 1000 / 60) % 60),
'seconds': Math.floor((time / 1000) % 60),
'total': time
};
};
function startTimer(counterDays, counterHours, counterMinutes, counterSeconds, date) {
var timerInterval = setInterval(function() {
var timer = updateTimer(date);
//Changes the text of the 'counter'
counterDays.innerHTML = timer.days;
counterHours.innerHTML = timer.hours;
counterMinutes.innerHTML = timer.minutes;
counterSeconds.innerHTML = timer.seconds;
window.onload = function() {
startTimer(counterDays, counterHours, counterMinutes, counterSeconds, date);
};
<span id="days"> </span>
<span id="hours"> </span>
<span id="minutes"> </span>
<span id="seconds"> </span>
What I seriously do not understand is why the updateTimer always needs date within the parentheses, when the variable date is an already existing variable within the global scope. Same with startTimer. I don't understand why I need to pass that in. Why not just access the variable within the function, as they do have a global scope, and be done with it. Instead I need to pass in the variable as a parameter, for the function to work.
I've tried and tried, but the only way to make the function work is by passing in the variables. Why is that???
As I am still learning, I've searched the internet for more information on functions and their parameters, but all show me something similar to my first example. I know this is all probably just going over my head, but for the life of me, I just do not understand.
Note: I am still learning, so sorry if this whole question is plain stupid.
Also, the the code for the JS that I am having a problem with won't actually run. This is due to me not wanting to put in all of my code, but rather just the code I am having trouble with.