How to limit the number of iterations done by setInterval

前端 未结 5 2258
别那么骄傲
别那么骄傲 2021-01-04 05:34

I display video ads to my users. I don\'t host these ads by the way; I get them from another company.

When ever an ad is clicked it leaves a cookie in the user\'s b

5条回答
  •  自闭症患者
    2021-01-04 06:18

    WindowTimers.setInterval(func, delay[, param1, param2, ...])

    The 3rd parameter and onward in setInterval are optional parameters to pass to the interval function. Note, these optional arguments are not supported in IE9 and earlier.

    We can use this to our advantage by avoiding the use of global or outside-scope. as seen below. The interval function keeps track of the limit and the current increment of the counter through the opts parameter.

    The runTask function takes a mandatory fn argument which returns a boolean value to determine if the timer's task has been completed. There are two taks that are run in the example below, with each varying in the rate at which each is run and the condition to be met.

    The first two tasks finish, but the last one runs out of attempts before the condition is met.

    function writeLine(el, text) {
      el.innerHTML += [].slice.call(arguments, 1).join(' ') + '\n';
    }
    
    function runTask(options, interval, limit) {
      var interval = setInterval(function(opts) {
        opts.incr = (opts.incr || 0) + 1;    
        if (opts.fn(opts)) {
          clearInterval(interval);
          writeLine(opts.el, '>> Task finished...');
        } else if (opts.incr > limit) {
          clearInterval(interval);
          writeLine(opts.el, '>> Exceeded limit of ' + limit);
        } else {
          writeLine(opts.el, '>> Attempt: ' + opts.incr + '/' + limit);
        }
      }, interval, options);
    }
    
    // 5 atttempts to reach 4 in 250ms.
    runTask({
      fn : function(opts) { return opts.incr === 4; },
      el : document.querySelectorAll('div.col')[0]
    }, 250, 5);
    
    // 10 atttempts to reach 7 in 100ms.
    runTask({
      fn : function(opts) { return opts.incr === 7; },
      el : document.querySelectorAll('div.col')[1]
    }, 100, 10);
    
    // 10 atttempts to reach 15 in 50ms.
    runTask({
      fn : function(opts) { return opts.incr === 15; },
      el : document.querySelectorAll('div.col')[2]
    }, 50, 10);
    .col {
      display: inline-block;
      width: 175px;
      font-family: monospace;
      white-space: pre;
      border: thin solid black;
      vertical-align: top;
      padding: 4px;
    }

提交回复
热议问题