skip
skip

Reputation: 12653

How to continuously check time in jQuery from a fixed time

I have a very simple problem in which I need to do something after 30 minute from a fixed time and then do something else after 30 minute 15 seconds from the same fixed time. I am using the following code to achieve that but it doesn't seem to work.

<script type="text/javascript" src="<c:url value="/resources/js/date.js" />"></script>

<script type="text/javascript" >
$(document).ready(function () {
    jQuery.ajax({
        url: "/wikedlynotsmart/creationTime",
        success: function (data) {
            var date = parseFloat(data.creationDate);
            var timeCreation = new Date(date);
            var timeAlert = new Date(timeCreation);
            timeAlert.setMinutes(timeCreation.getMinutes() + 30);
            var timeAutoSubmit = new Date(timeCreation);
            timeAutoSubmit.setMinutes(timeCreation.getMinutes() + 30);
            timeAutoSubmit.setSeconds(timeCreation.getSeconds() + 15);
            setInterval(function () {
                if (new Date() == timeAlert) {
                    alert("time is over");
                }
                if (new Date() == timeAutoSubmit) {
                    $('form').submit();
                }
            }, 1000);
        },
        async: false,
        dataType: "json"
    });
});
</script>

Could someone help me understand am I doing wrong here?

Thanks.

EDIT: "Time's up! has been edited to "time is over" but still it does not work.

Upvotes: 0

Views: 726

Answers (2)

Alnitak
Alnitak

Reputation: 339836

Don't count once a second, if you can avoid it. AFAIK you also can't compare Date() objects like that.

Work out the initial delay between 30 minutes after the returned time and now, and wait that long. Then wait another 15 seconds.

var create = new Date(data.creationDate).getTime() + (30 * 60 * 1000);
var now = new Date().getTime();

var delay = Math.max(0, create - now);  // initial delay
setTimeout(function() {
    console.log("Time's up!");  // not alert() - that blocks the UI
    setTimeout(function() {
        $('form').submit();
    }, 15000);
}, delay);

Upvotes: 2

Grim...
Grim...

Reputation: 16953

Will

setTimeout('myFunction();',1800000);

not work?

(1,800,000 is 30 minutes in milliseconds).

Upvotes: 0

Related Questions