'How to use a value from an element to set the interval in setInterval

I have a page that shows the people that accepted to come to an event along with some details about them. These people accept by filling in a form which is then submitted to a database. My page basically makes an AJAX request to it and fetches all the relevant data which then sorts them out to a readable layout.

I am trying to add the option for the person viewing this page to set a refresh rate - that is, the time before remaking the AJAX request each time. For instance one may choose 30 seconds, so the page each time 30 seconds pass makes another AJAX request and overwrites the old data...

What I did was have dropdown box with some choices (60secs, 120secs, and so on). When the section loads the javascript containing the AJAX call gets the value from the dropbox and uses it as a parameter in the setInterval function, like this

recurring = setInterval(function() {
                            getSchedule(dateText.trim());
                        },
                        $('input[type=hidden]#rr').val());

but the requests are non-stop. At first I thought the problem may be that the result of the JQuery selection is string when the argument expected should be number so I tried

recurring = setInterval(function() {
                            getSchedule(dateText.trim());
                        },
                        parseInt($('input[type=hidden]#rr').val(),10));

but still nothing. I don't know if it means anything but when testing this code (when I was trying to see what type the value was)

var interval = parseInt( $('input[type=hidden]#rr').val() , 10 );
alert( typeof ( interval ) + ' -- ' + interval );

the alert box writes

number -- NaN

Any ideas anyone?

Okay, this is an edit to show the html code

<div class='fields'>
    <input type='hidden' name='rr' id='rr' value='<?php if ( $_SESSION['rr'] != 0 ) echo $_SESSION['rr']*1000; else echo 86400000;  ?>'/>
    <div style='float:left; padding-top:5px;'>
        <b><i>TIME</i></b>
    </div>
</div>
<div id='schedule' style='overflow:auto;'>
</div>

This is the section where the data is presented. The AJAX result goes into the schedule div and is the one updated. The hidden field contains the milliseconds for the interval and is where I get it from using JQuery. It is in a database stored and when this page is loaded there is some communication with the database and get it from there and the save it in the session array



Solution 1:[1]

once you use the setInterval, unless you explicitly call clearInterval, it will continue to call the your function.

Instead, I'd recommend you should use [setTimeout] like this

setInterval(function () {
    getSchedule(dateText.trim());
},
$('input[type=hidden]#rr').val());

and in your function getSchedule, call setInterval again. This way, every time the function executes, it sets the time period for itself.

function getSchedule(...){
   ...
   setInterval(function () {
        getSchedule(dateText.trim());
    },
    $('input[type=hidden]#rr').val());
}

As far as the input value is concerned, I cannot comment until I see your HTML

Solution 2:[2]

[updated] A few comment's that might help but not solve your problem:

for your selection, since you are using id, you should select directly (faster) :

parseInt($('#rr').val()); // by default the base is 10

note: you don't have to use typeof since you are always parsing to int, it will be always a number

I think maybe your problem is related to that value, does it exist? can you inspect the page and check what the value is as an html ?

Solution 3:[3]

So I never did understand why the value was read wrong, maybe the browser used the cache and loaded javascript before the changes... Anyway my final solution with the help of the above that works is the following

$(document).ready(function() {
    $('#datepicker').datepicker( {
        showOtherMonths: true,
        selectOtherMonths: true,
        dateFormat: 'yy-mm-dd',
        inline: true,
        onSelect: function(dateText, inst) {
                getSchedule(dateText.trim());
        }
    });

    var timeout;
    var today = $('#datepicker').datepicker('getDate');
    getSchedule($.datepicker.formatDate('yy-mm-dd', today));
});

function getSchedule(date)
{   
    if ( 'undefined' === typeof(timeout) ) ; else clearTimeout(timeout);
    timeout = setTimeout(function() {
                            getSchedule(date);
                        },
                        parseInt($('input[type=hidden]#rr').val(), 10)
                        );


    var request = $.ajax({
        type    : 'POST',
        url     : './scripts/php/schedule.php',
        data    : { date: date }
    });

    request.done(function(data,textStatus,jqXHR) {
        var height = $(window).height()-150;
        $("#schedule").height(height).html(data);
        }
    });

    request.fail(function(jqXHR, textStatus, errorThrown) {
    }); 
}

and the html

<div class='fields'>
        <input type='hidden' name='rr' id='rr' value='<?php if ( $_SESSION['rr'] != 0 ) echo $_SESSION['rr']*1000; else echo 86400000;  ?>'/>
        <div style='float:left; padding-top:5px;'>
            <b><i>TIME</i></b>
        </div>

</div>
<div id='schedule' style='overflow:auto;'>
</div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 U.P
Solution 2
Solution 3 Andreas Andreou