Javascript 使用setTimeout跳过第一次出现

Javascript 使用setTimeout跳过第一次出现,javascript,Javascript,我希望执行console.log()仅在时间到期后重复,但不在页面加载后立即重复。这是如何实现的 function setTimer(t) { (function timeout() { console.log('timer '+t+' seconds') setTimeout(timeout, t*1000); })(); } setTimer(5); setTimer(10); setTimer(15); setTimer(20); 仅使用设置间隔: 您可以使用s

我希望执行
console.log()仅在时间到期后重复,但不在页面加载后立即重复。这是如何实现的

function setTimer(t) {
  (function timeout() {
    console.log('timer '+t+' seconds')
    setTimeout(timeout, t*1000);
  })();
}

setTimer(5);
setTimer(10);
setTimer(15);
setTimer(20);

仅使用设置间隔:

您可以使用setInterval,它将在预定义的时间段内反复执行。下面的示例将每秒打印“Hello there”

var myID = setInterval(function(){
  console.log('Hello there');
},1000);
要停止设置间隔,需要使用以下命令:

clearInterval(myID);

仅使用设置超时:

您还可以使用setTimeout并调用一个将调用自身的函数。下面的示例将在1秒后执行,然后在控制台中每秒重复打印“Hello here”

    setTimeout(function(){
      CallMyself();
    },
 // Set the Execution to take place exactly 1000 ms after it has been called.
    1000);

    function CallMyself(){
      console.log('Hello There');
      setTimeout(function(){
        CallMyself();
      },
  // Set the period of each loop to be 1000 ms
     1000);
    }

将两者结合使用

您还可以将setIntervalsetTimeOut组合使用。以下示例将在1秒后开始每隔一秒打印一次“Hello There”

  setTimeout(function(){
    setInterval(function(){
      console.log('Hello there');
    },1000);
  },1000);

将初始延迟和循环延迟作为参数以便创建不同计时器的函数示例:

//  First argument is the Delay in Execution. 
//  Second argument is the period it takes for each loop to be completed. 
setCustomTimer(1,2);
设置自定义定时器(2,4);
函数setCustomTimer(initialDelay、LoopDelay){
log('initialDelay+'Seconds'的初始延迟);
var myDelay=LoopDelay;
setTimeout(函数(){
log('+initialDelay+'秒的初始延迟结束。开始循环');
叫我自己(myDelay);
},初始延迟*1000);
}
函数callimf(LoopDelay){
log('Loop every'+LoopDelay+'Seconds');
setTimeout(函数(){
呼叫我自己(延迟);
},循环延迟*1000);

}
以下内容如何:

function MyLoop(t) {
  setTimeout(function() {
    console.log('Loop '+t+' seconds.')
    MyLoop(t);
  }, t * 1000);
}

MyLoop(5);
MyLoop(10);
MyLoop(15);
MyLoop(20);

document.ready
callback一起使用。@KonstantinAzizov
setInterval
有它的问题,我不想使用它。为什么要进行标记?使用
setTimeout()
是如何实现的(您的第二个示例)?它立即执行,这正是我想要阻止的。setTimeOut根据传递给它的值执行。在我的示例中,setTimeOut在调用后1秒执行。尽管如此,我还是添加了一小部分代码,您可以根据需要进行调整。检查第二个示例。哼两个
setTimeout()
函数。它看起来有点复杂,可能会使用您的第一种方法,但稍作修改。我还不确定在我的示例中如何设置任意数量的计时器(例如,我展示的示例中有5、10、15和20秒,但在这样的连续时间段中可能会有更多,而不是更多)。两个设置超时不是问题,第一个只是为了简单的延迟。我在第四个示例中添加了一个函数,请查看。你应该能够从那里继续下去,扩展到你喜欢的领域。