首页 > 解决方案 > 如何在 javascript 的一个函数中使用 setTimeOut 和 setInterval

问题描述

使用递归和 setTimeout 编写一个函数 customSetInterval(funcToExecute, interval),它将重复 setInterval 内置方法的功能 setInterval 内置方法有两个参数:第一个参数是一个在给定时间间隔运行的函数第二个参数是以毫秒为单位的时间间隔。

 function to call:
 function executeMe () {
     console.log ('123')
 }

 example of calling your function:
 customSetInterval (executeMe, 1000)
 as a result, the 123 line will be displayed in the console every second

从下面的评论中提取:

function customSetInterval(funcToExecute, interval) {
    setTimeout(function() {
        function executeMe() {
            console.log('123');
            customSetInterval();
        }
    }, 1000)
};
customSetInterval(funcToExecute, 1000);

标签: javascript

解决方案


我想这就是你想要的:

function executeMe() {
  console.log('123');
}

function customSetInterval(fn, time) {
   setTimeout(function() {
    fn();
    customSetInterval(fn, time)
   }, time);
}


customSetInterval (executeMe, 1000);


推荐阅读