Last active
December 11, 2015 18:27
-
-
Save sagiavinash/7eb9bdf233270085a107 to your computer and use it in GitHub Desktop.
Utility function to create a setInterval with its running status available
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* problem:: there is no way to know if a setInterval is cleared or still running. | |
* with the following utility function you can create a trackable setInterval. | |
* http://jsbin.com/dakewamihi/edit?js,console | |
*/ | |
/* definition */ | |
function setTrackableSetInterval(logicFn, delay, trackerObj) { | |
var trackerIndex = 0; | |
trackerObj.status = true; | |
var trackerTimerId = setInterval(function() { | |
if (!trackerIndex || trackerObj.status) { | |
trackerObj.status = false; | |
trackerIndex++; | |
} else { | |
clearInterval(trackerTimerId); | |
} | |
}, delay); | |
trackerObj.timerId = setInterval(function() { | |
trackerObj.status = true; | |
logicFn(); | |
}, delay); | |
} | |
/* usage */ | |
var tracker = {}; | |
// Invocation | |
setTrackableSetInterval(function() { | |
// do something; | |
}, 1000, tracker); | |
// clearing Interval; | |
setTimeout(function() { | |
clearInterval(tracker.timerId); | |
}, 5000); | |
// get status setTrackableSetInterval; | |
var loggerTimerId = setInterval(function(){ | |
console.log("Interval " + (tracker.status ? "running" : "stopped")); | |
}, 500); | |
setTimeout(function() { | |
clearInterval(loggerTimerId); | |
}, 6000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment