javascript - 如何在 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);
解决方案
我想这就是你想要的:
function executeMe() {
console.log('123');
}
function customSetInterval(fn, time) {
setTimeout(function() {
fn();
customSetInterval(fn, time)
}, time);
}
customSetInterval (executeMe, 1000);
推荐阅读
- html - Bootstrap 4等高列不起作用
- c++ - 为什么包含需要进一步的依赖?
- sql - SQL CASE WHEN THEN 计算列类型的逻辑
- c# - 创建变量时会发生什么?
- sql - 如何存储 SQL Server 中给出的 NUMERIC 值
- azure-stream-analytics - Azure 流分析作业挂起或不处理输入
- javascript - 如何在 VueJS 中单击按钮 B 时启用按钮 A?
- magento - Magento 分页无法正常工作
- triggers - 我的点击触发器总是在谷歌标签管理器中触发
- autodesk-viewer - 在 viewer.loadModel 方法中使用 options.ids 参数来选择模型中的对象子集