Anurag Singh
Anurag Singh

Reputation: 727

Javascript Date not giving tupdated value

here i was making a sample program in php.In which i included the java script and used the date but i am getting the same date every time.let have a look on the code.

<?php
?>

<html>
<head>
    <title>my app</title>
    <script type="text/javascript" src="jquery-2.0.2.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            var time1=new Date();
            var time_stack=new Array();
            var time;
            $(this).mousemove(function(){
                time=time1.getSeconds();
                alert(time1);
            });
        });

    </script>
</head>
<body>
<h2>we are on the main_session</h2>
</body>
</html>

now the problem is that when i move the mouse than i get an alert box popping out and the date which is being displayed is same all time.Please let me know the problem

Upvotes: 3

Views: 82

Answers (6)

Deepak Bhatt
Deepak Bhatt

Reputation: 21

Hi, You should assign value for time1 variable in the mousemove() function. Use like this:

$(this).mousemove(function(){
    var time1 = new Date();
    var time_stack = new Array();
    var time;
    time = time1.getSeconds();
    alert(time1);
});

Upvotes: 1

Enam
Enam

Reputation: 1268

There is a misprint: alert(time), not time1 and try this:

$(this).mousemove(function(){
                var time1=new Date();
                time=time1.getSeconds();
                alert(time);
            });

Upvotes: 0

Sonu Sindhu
Sonu Sindhu

Reputation: 1792

Try this

        $(document).ready(function(){
            $(this).mousemove(function(){
                var time1=new Date();
                time=time1.getSeconds();
                alert(time);
            });
        });

Hope it will help

Upvotes: 1

Louis Ricci
Louis Ricci

Reputation: 21086

The Date object your instancing isn't a stop watch that will get the current time when you call a method on it. You need to instances a new Date object in your event handler.

alert(new Date().getSeconds());

Upvotes: 0

adeneo
adeneo

Reputation: 318182

The variable time1 never changes, the Date object is the same, so you always get the same time ?

You have to either update the Date on each mousemove, or just get a new Date object :

<html>
<head>
    <title>my app</title>
    <script type="text/javascript" src="jquery-2.0.2.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $(this).mousemove(function(){
                var time1 = new Date();
                console.log( time1.getSeconds() );
            });
        });

    </script>
</head>
<body>
<h2>we are on the main_session</h2>
</body>
</html>

FIDDLE

Upvotes: 0

Uku Loskit
Uku Loskit

Reputation: 42040

This is because time1 is evaluated only once when the page loads, on every mouse event you just get the seconds from when it was initialized

Upvotes: 0

Related Questions