开发者

Problem with setInterval to call function

I'm trying to get a simple script to work, but somewhere I must have done something wrong because it's not working! I just want to set an interval timing that call a function. Preciate some help. Perhaps not the best solution, but I'm new to this.

$(document).ready(function() {

startInterval(); // activate timer

function start开发者_如何学GoInterval() {
var t = setInterval("autoSave", 20000);
}

function autoSave() {
alert("test");
}

});


Either one of these will work, but not what you have

// Pass the real function
function startInterval() {
  var t = setInterval(autoSave, 20000);
}

// THIS MAY NOT WORK
// eval
function startInterval() {
  var t = setInterval("autoSave()", 20000);
}
//

// Anonymous function
function startInterval() {
  var t = setInterval(function() { autoSave(); }, 20000);
}

Here's the reasoning: If you pass a function directly, it will call it. However, if you pass a string, it will to eval it when the timeout is up - which returns a function in your case, and in my second case returns the evaluated function (notice the parenthesis)


Remove "", and make it a reference to the function.

function startInterval() {
  var t = setInterval(autoSave, 20000);
  //                  ^now you have a reference to
  //                   autoSave and setInterval knows
  //                   what to execute
}


1) better practice is to make t - global, otherwise it won't be accessible outside startInterval() function. But you'll need it to clear interval

i.e. declare var t; before function startInterval();

2) consider: t = setInterval('autoSave()', 20000);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜