运行功能30分钟

时间:2013-04-30 04:40:54

标签: javascript javascript-events timer range

这就是我想要做的。

  1. 执行一个功能:一次,在一天的某个时间。
  2. 该功能运行30分钟。
  3. 我已尝试过setTimeout,但它不符合我的要求,因为它在 X 毫秒之后运行该函数。而我需要立即执行该功能,在所需的时间执行30分钟。代码附后。

    var d = new Date(); 
    var hour = d.getHours();
    var minute = d.getMinutes();
    var day  = self.getDate();
    
    var month_name=new Array(12);
    month_name[0]="January"
    month_name[1]="February"
    month_name[2]="March"
    month_name[3]="April"
    month_name[4]="May"
    month_name[5]="June"
    month_name[6]="July"
    month_name[7]="August"
    month_name[8]="September"
    month_name[9]="October"
    month_name[10]="November"
    month_name[11]="December"
    
    var month = month_name[self.getMonth()];
    var fullDate = month+' '+day+' '+hour+':'+minute;
    
    function someFunction() {}
    
    function closeFunction(){
       noticeDiv.css('display', 'block');
       mainDiv.css('display', 'none');
    }
    
    function executeFunction(targetDate){
       if (fullDate == targetDate){
         setTimeout ( closeFunction(), 180000 );
       }else{
         someFunction();
       }
    }
    
    executeFunction(targetDate);
    

1 个答案:

答案 0 :(得分:0)

使用setInterval函数

Syntax-> var interval = setInterval(function(){function_name()},timeout(以毫秒为单位);

要清除我们使用的间隔或停止功能 - > clearInterval(interval);

HTML

<!-- Hide by default, show at target time -->
<div id="noticeDiv" style="display: none">
        <h2>Registration Closed.</h2>

</div>
<!-- Show by default, hide at target time -->
<div id="mainDiv">
        <h2>Registration Open.</h2>

</div>

的jQuery

$(document).ready(function () {
    var d = new Date();
    var hour = d.getHours();
    var minute = d.getMinutes();
    var day = d.getDate();

    var month_name = new Array(12);
    month_name[0] = "January"
    month_name[1] = "February"
    month_name[2] = "March"
    month_name[3] = "April"
    month_name[4] = "May"
    month_name[5] = "June"
    month_name[6] = "July"
    month_name[7] = "August"
    month_name[8] = "September"
    month_name[9] = "October"
    month_name[10] = "November"
    month_name[11] = "December"

    var month = month_name[d.getMonth()];
    var fullDate = month + ' ' + day + ' ' + hour + ':' + minute;
    console.log(fullDate);
    fulldate = 'May 3 17:1';

    function executeFunction(targetDate) {
        x = 0;
        if (fulldate == targetDate) {

//设置功能关闭时间180000 = 30分钟。它会隐藏div注册打开并显示注册关闭div。

        interval = setInterval(closeFunction, 180000); 
        } else {
            openFunction();
        }
    }

    function openFunction() {
        console.log('Registration is now open')
    }

    function closeFunction() {
        x++;
        $('#mainDiv').append(x);
        if (x == 1) {
            $('#noticeDiv').show();
            $('#mainDiv').hide();
            clearInterval(interval);
        }
    }
    // Execute time
    executeFunction('May 3 17:1');
});

工作演示http://jsfiddle.net/cse_tushar/8r5T8/