2017-04-19 34 views
0

我想执行的代码块每两秒钟,完成这一系统的时间,我想最简单的方法是获取当前的系统时间,像这样:检索不断更新的JavaScript

if ((Date().getSeconds()) % 2 == 0) { 
    alert("hello"); //I want to add code here! 
} 

然而,我的警报不会每两秒钟打印到屏幕上。这怎么能正确实施?

+1

你有没有尝试https://www.w3schools.com/jsref/met_win_setinterval.asp – cabolanoz

+0

啊哈!我没有尝试过。也许这是我最好的选择... – Eragon20

回答

2

为了每x秒运行一段代码,可以使用setInterval。 下面是一个例子:

setInterval(function(){ 
    alert("Hello"); 
}, x000); // x * 1000 (in milliseconds) 

这里有一个工作片断:

setInterval(function() { 
 
    console.log("Hello"); 
 
}, 2000);

1

可以使用的setInterval()。这将每2秒循环一次。

setInterval(function() { 
    //something juicy 
}, 2000); 
1

这应该适合你。

setInterval(function() { 
    //do your stuff 
}, 2000) 

但是,要回答为什么你的代码不工作,因为它不在循环中。

runInterval(runYourCodeHere, 2); 

function runInterval(callback, interval) { 
    var cached = new Array(60); 
    while (true) { 
    var sec = new Date().getSeconds(); 
    if (sec === 0 && cached[0]) { 
     cached = new Array(60); 
    } 

    if (!cached[sec] && sec % interval === 0) { 
     cached[sec] = true; 
     callback(); 
    } 
    } 
} 

function runYourCodeHere() { 
    console.log('test'); 
} 
1

尝试使用setInterval()方法

setInterval(function() {console.log('hello'); }, 2000)