简体   繁体   English

如何使用元素中的值设置setInterval中的间隔

[英]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. 我的页面基本上向它发出AJAX请求,并获取所有相关数据,然后将它们分类为可读的布局。

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. 我正在尝试为查看此页面的人添加选项以设置刷新率-即每次重新生成AJAX请求之前的时间。 For instance one may choose 30 seconds, so the page each time 30 seconds pass makes another AJAX request and overwrites the old data... 例如,可能选择30秒,因此每次经过30秒时页面都会发出另一个AJAX请求并覆盖旧数据...

What I did was have dropdown box with some choices (60secs, 120secs, and so on). 我所做的是使用下拉框进行一些选择(60秒,120秒等等)。 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 当该部分加载包含AJAX调用的javascript时,会从Dropbox中获取值并将其用作setInterval函数中的参数,例如

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 起初我以为问题可能是当期望的参数应该是数字时,JQuery选择的结果是字符串,所以我尝试了

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 数字-NaN

Any ideas anyone? 有任何想法吗?

Okay, this is an edit to show the html code 好的,这是一个显示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>

This is the section where the data is presented. 这是显示数据的部分。 The AJAX result goes into the schedule div and is the one updated. AJAX结果进入进度表div,并且已更新。 The hidden field contains the milliseconds for the interval and is where I get it from using JQuery. 隐藏字段包含该间隔的毫秒数,这是我通过使用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 它存储在数据库中,并且在加载此页面时,与数据库进行一些通信,然后从那里获取并将其保存在会话数组中

once you use the setInterval , unless you explicitly call clearInterval , it will continue to call the your function. 一旦使用setInterval ,除非您显式调用clearInterval ,否则它将继续调用您的函数。

Instead, I'd recommend you should use [setTimeout] like this 相反,我建议您应使用[setTimeout]这样

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

and in your function getSchedule , call setInterval again. 然后在您的函数getSchedule ,再次调用setInterval。 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 就输入值而言,直到看到您的HTML,我才能发表评论

[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) : 作为选择,由于您使用的是ID,因此您应该直接(更快)选择:

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 注意:您不必使用typeof,因为您始终会解析为int,它将始终是一个数字

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 ? 您可以检查页面并检查html的值是什么吗?

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 因此,我从来没有理解过为什么值读错了,也许浏览器在更改之前使用了缓存并加载了javascript ...无论如何,在上述有效的帮助下,我的最终解决方案如下

$(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 和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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM