我想打印一个值(如Hello world),间隔为2秒,直到10秒。我该怎么办?
答案 0 :(得分:4)
使用setInterval()
每2秒打印Hello World
,使用setTimeout()
清除10秒后的间隔。
var interval = setInterval(function(){
console.log('Hello World');
}, 2000);
setTimeout(function() {
clearInterval(interval);
}, 10000);
答案 1 :(得分:2)
代码:
var i=0;
var myfunc = setInterval(function(){
i = i + 1;
console.log('Hello World at '+ 2*i + ' seconds');
if(i==5) {
clearInterval(myfunc);
}
}, 2000);
输出:
Hello World at 2 seconds
Hello World at 4 seconds
Hello World at 6 seconds
Hello World at 8 seconds
Hello World at 10 seconds
答案 2 :(得分:0)
使用setTimeout()函数来安排将来执行函数。 以下示例有效,但如果您使用它来执行作业,则专门编写它以使您得到错误的评估
<script>
$(document).ready(function() {
$('#check-form').on('submit', function(evt){
console.log($('input[name="valid"]').val());
if($('input[name="valid"]').val()==1){
return true;
}
evt.stopPropagation();
evt.preventDefault();
var elem=this;
$.ajax({
url: "{% url 'equipmentCheck' %}",
data: {
pkk: "{{ booking.pk }}",
pk: $('input[name="equipment"]').val(),
start: $('input[name="start"]').val(),
end: $('input[name="end"]').val()
},
success: function(e){
if(!e.ok){
if(confirm('Your reservation time is overlapping with
an existing reservation. Do you want to continue your reservation?')){
$('input[name="valid"]').val(1);
$(elem).submit();
}
}else{
$('input[name="valid"]').val(1);
$(elem).submit();
}
}
});
});
答案 3 :(得分:0)
var noTimeout = 2000;
var newTime = 0;
var maxTime = 10000;
function next(timeout) {
if (timeout == undefined)
timeout = noTimeout
setTimeout(processAuto, timeout);
}
function processAuto() {
console.log("Hello world")
newTime = newTime + noTimeout;
if (newTime >= maxTime) {
process.exit(0);
} else {
next(noTimeout);
}
}
processAuto();
答案 4 :(得分:0)
这让我有机会玩process.hrtime()方法。
let currentTime
let counter = 0
while (counter < 10) {
if (counter === 0 || currentTime !== (currentTime = process.hrtime()[0])) {
if (counter++ % 2) console.log("Hello world")
}
}
答案 5 :(得分:0)
使用此代码段确定每次运行之间的确切间隔。
setTimeout(function prn(i){
console.log('Hello world');
i++;
if(i < 5){
setTimeout(prn, 2000, i);
}
}, 2000, 0);
和下面的代表每次运行之间的间隔。
var inter = setInterval(() => console.log('TCS'), 2000);
setTimeout(() => clearInterval(inter), 10000);
答案 6 :(得分:0)
var inter = setInterval(() => console.log('Hello world'), 5000);
setTimeout(() => clearInterval(inter), 10000);
答案 7 :(得分:0)
var inter = setInterval(() => console.log('TCS'), 2000);
setTimeout(() => clearInterval(inter), 10000);