Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
<div id="time">30</div>
</body>
</html>
 
var timerInit = function(cb, time, howOften) {
  // time passed in is seconds, we convert to ms
  var convertedTime = time * 1000;
  var convetedDuration = howOften * 1000;
  var args = arguments;
  var funcs = [];
  
  for (var i = convertedTime; i > 0; i -= convetedDuration) {
    (function(z) {
      // create our return functions, within a private scope to preserve the loop value
      // with ES6 we can use let i = convertedTime
      funcs.push(setTimeout.bind(this, cb.bind(this, args), z));
      
    })(i);
  }
   
  // return a function that gets called on load, or whatever our event is
  return function() {
    
    //execute all our functions with their corresponsing timeouts
    funcs.forEach(function(f) {
      f();
    });
  };
  
};
// our doer function has no knowledge that its being looped or that it has a timeout
var doer = function() {
  var el = document.querySelector('#time');
  var previousValue = Number(el.innerHTML);
  document.querySelector('#time').innerHTML = previousValue - 1;
};
// call the initial timer function, with the cb, how many iterations we want (30 seconds), and what the duration between iterations is (1 second)
window.onload = timerInit(doer, 30, 1);
Output

This bin was created anonymously and its free preview time has expired (learn why). — Get a free unrestricted account

Dismiss x
public
Bin info
anonymouspro
0viewers