有没有办法在JavaScript中定期调用函数?

时间:2009-08-03 20:31:23

标签: javascript javascript-events

有没有办法在JavaScript中定期调用函数?

9 个答案:

答案 0 :(得分:189)

您想要setInterval()

var intervalID = setInterval(function(){alert("Interval reached");}, 5000);

setInterval()的第一个参数也可以是要评估的代码字符串。

您可以使用以下方法清除周期性功能:

clearInterval(intervalID);

答案 1 :(得分:33)

请注意,setInterval()通常不是定期执行的最佳解决方案 - 真的取决于您实际定期调用的javascript。

例如。如果你使用周期为1000毫秒的setInterval()并在周期函数中进行ajax调用,偶尔需要2秒才能返回,你将在第一个响应返回之前再进行一次ajax调用。这通常是不受欢迎的。

许多库都有定期的方法来防止使用setInterval的天真陷阱,例如Nelson给出的Prototype示例。

要使用包含jQuery ajax调用的函数实现更强大的定期执行,请考虑以下内容:

function myPeriodicMethod() {
  $.ajax({
    url: ..., 
    success: function(data) {
      ...
    },
    complete: function() {
      // schedule the next request *only* when the current one is complete:
      setTimeout(myPeriodicMethod, 1000);
    }
  });
}

// schedule the first invocation:
setTimeout(myPeriodicMethod, 1000);

另一种方法是使用setTimeout但跟踪变量中的已用时间,然后动态设置每次调用的超时延迟,以尽可能接近所需的时间间隔执行函数,但绝不会比获得响应更快。

答案 2 :(得分:15)

每个人都有一个setTimeout / setInterval解决方案。我认为重要的是要注意你可以将函数传递给setInterval,而不仅仅是字符串。它实际上可能有点“安全”传递真正的函数而不是那些将被“唤醒”到那些函数的字符串。

// example 1
function test() {
  alert('called');
}
var interval = setInterval(test, 10000);

或者:

// example 2
var counter = 0;
var interval = setInterval(function() { alert("#"+counter++); }, 5000);

答案 3 :(得分:3)

是 - 请查看setInterval and setTimeout以便在特定时间执行代码。 setInterval将是用于定期执行代码的那个。

查看demo and answer here的使用情况

答案 4 :(得分:3)

您需要查看setInterval()和setTimeout()。

这是decent tutorial article

答案 5 :(得分:3)

老问题但是...... 我还需要一个期刊任务跑步者并写下TaskTimer。当您需要在不同的时间间隔上运行多个任务时,这也很有用。

// Timer with 1000ms (1 second) base interval resolution.
var timer = new TaskTimer(1000)

// Add task(s) based on tick intervals.
timer.addTask({
    name: 'job1',       // unique name of the task
    tickInterval: 5,    // run every 5 ticks (5 x interval = 5000 ms)
    totalRuns: 10,      // run 10 times only. (set to 0 for unlimited times)
    callback: function (task) {
        // code to be executed on each run
        console.log(task.name + ' task has run ' + task.currentRuns + ' times.');
    }
});

// Start the timer
timer.start();

TaskTimer适用于浏览器和Node。有关所有功能,请参阅documentation

答案 6 :(得分:2)

function test() {
 alert('called!');
}
var id = setInterval('test();', 10000); //call test every 10 seconds.
function stop() { // call this to stop your interval.
   clearInterval(id);
}

答案 7 :(得分:1)

由于您希望定期执行功能,请使用setInterval

答案 8 :(得分:1)

原生方式确实是setInterval() / clearInterval(),但如果您已经在使用Prototype库,则可以利用PeriodicalExecutor:

new PeriodicalUpdator(myEvent, seconds);

这可以防止重叠呼叫。来自http://www.prototypejs.org/api/periodicalExecuter

  

“它可以防止多次并行执行回调函数,如果执行的时间超过给定的时间间隔(它维护一个内部的”运行“标志,它可以屏蔽回调函数中的异常)。如果您使用一个以给定的时间间隔与用户交互(例如使用提示或确认呼叫),这将非常有用:这将避免所有等待操作的多个消息框。“

相关问题