在调用函数时在javascript中设置一个计时器

时间:2013-07-22 13:50:26

标签: javascript jquery

我想在javascript中设置一个计时器,以便在半秒钟内执行一个函数,条件是如果时间超过两分钟,计时器应该停止:

我的代码:

  function InitialiseCountDown() {
    var x =setInterval(function(){
          CreateImage();
       },500);
          if(x== ? ) // what should i do here to make sure the two minites are done 
           {
         ClearInterval(x);
            }
     }

2 个答案:

答案 0 :(得分:3)

function InitialiseCountDown() {
    var start = +new Date();
    var x = setInterval(function(){
        CreateImage();
        if(+new Date() - start > 2 * 60 * 1000) {
            clearInterval(x);
        }
    },500);
}

答案 1 :(得分:1)

你应该试试

 function InitialiseCountDown() {
    var x =setInterval(function(){
              CreateImage();
           },500);

    setTimeout(function( ) {
        clearInterval( x ); 
           },  2000*60);

 }