0

I'm trying to create a timer in javascript. The sec variable won't increment. Any idea why this is happening?

<script>
var sec = 0;

setInterval(function () {
    start_timer();
}, 1000);

function start_timer() 
{
        sec++;          
}
</script>

How I call the variable:

First, I have a form that calls getCurrentTime()

<button type="button" onclick=" <?php getCurrentTime(); ?>"  class="unstyled-button imageButtonLeft" >

getCurrentTime stores the sec variable into setTime(), then I use getTime() to print it.

function getCurrentTime()
{
    //Unserialize
    $s1 = file_get_contents('store');
    $moodCalculator = unserialize($s1);

    $time = "<script>document.writeln(sec);</script>";
    $moodCalculator->setTime($time);

    //Serialize
    $s1 = serialize($moodCalculator);
    file_put_contents('store', $s1);
}

echo $moodCalculator->getTime();

Is it maybe possible that getCurrentTime() is getting called after the form has already been sent? 'Cause that would explain why "sec" results to 0 when I print it.

  • 5
    What makes you think `sec` isn't incrementing? Seems to be incrementing just fine for me – Nick Parsons Mar 25 '20 at 10:12
  • 1
    ^^ since nothing is using `sec`...? Also, just FWIW, there's no need for the wrapper function there... – T.J. Crowder Mar 25 '20 at 10:12
  • your code works fine , the problem is from somewhere else , you should give more detail on how you are using this in your scripts – Iman Emadi Mar 25 '20 at 10:14
  • @BrighFaith I have added further information. If I execute start_timer() manually, my code will print 1, that is why I think is setInterval that doesn't work. – CortoMaltese Mar 25 '20 at 10:29

0 Answers0