How to pass a variable to setInterval?

2019-02-21 06:33发布

问题:

I need to update the time in my setInterval. The value is returned by the function that setInterval is executing.

read_log(); returns an integer.

var loop = setInterval(function(){count = read_log();}, count);

This returns that count is undefiend. So I need to get the count and pass it to setInterval

回答1:

If you need to change the repetition interval after each call to read_log(), you can't use setInterval() -- that uses a constent repetition. You need to use setTimeout, so you can change the period each time:

function call_read_log() {
    var count = read_log();
    setTimeout(call_read_log, count);
}
call_read_log();