dgamma3
dgamma3

Reputation: 2371

javascript using global variables

can't seem to get this to work.

 var current_times = new Date();
 var future_times = new Date();

 function time(){
 current_times = current_times.setMinutes(current_times.getMinutes());
 future_times = future_times.setMinutes(future_times.getMinutes() + 1);     
 }

error im getting is: current_times.getMinutes is not a function

note sure this helps, but the time function is called from a function which is initiated on body load.

Upvotes: 2

Views: 443

Answers (2)

David Tang
David Tang

Reputation: 93694

The problem is that setMinutes returns a number, not a Date object.

The function will work the first time you call it, but on the second call current_times and future_times will be numbers, and hence won't have the getMinutes function. Since setMinutes() modifies the Date object instead of producing a new one, the solution is to not reassign your variables.


Furthermore, if I understand your intentions correctly, your code can be simplified to:

var current_times, future_times = new Date();

function time() {
    current_times = new Date();
    future_times.setMinutes(current_times.getMinutes() + 1);
}

Upvotes: 5

Mhmd
Mhmd

Reputation: 5167

the code is right but as Box9 typed code

you must assign variables inside the function to be like that'

function time() {
     var current_times = new Date();
     var future_times = new Date();

     current_times = current_times.setMinutes(current_times.getMinutes());
     future_times = future_times.setMinutes(future_times.getMinutes() + 1);     

     document.write(current_times);
     document.write("<br>"+future_times);
}

Upvotes: 0

Related Questions