0

这就是我想做的。

  1. 执行一个功能:一次,一天中的某个时间。
  2. 该函数运行 30 分钟。

我已经尝试过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);
4

1 回答 1

0

使用 setInterval 函数

语法-> 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/

于 2013-04-30T05:52:40.230 回答