Last active
January 10, 2022 16:53
-
-
Save uncledevhq/a1668b3eb55d53923de887d378bf4582 to your computer and use it in GitHub Desktop.
Learning closures with experiments. Javascript the hard partsyes the Hapas
This file contains 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
console.log("thenxtlvls 🚀 ", 2022); | |
// using clousures create a function that tracks how many times it's been called | |
// and exit when limit is reached. Reset the counter back to zero. | |
function functionCreatorWithLimit(limit) { | |
let counter = 0; | |
function functionToBeCalledWithDefinedLimit () { | |
if (counter >= limit ) { | |
console.log(`Limit of (${counter}) calls is reached, the counter has rested back to zero and you can run again`) | |
counter = 0; | |
// [Todo]// counter = 0; //should be able to uncomment to allow function to re-run after limit 😩 | |
return 0; | |
} | |
counter++; | |
console.log(`its run ${counter} time(s)`); | |
return counter; | |
} | |
return functionToBeCalledWithDefinedLimit; | |
} | |
const functionCaller = functionCreatorWithLimit(4); | |
// calling a function using sentInterval | |
const intervalFunctionCaller = setInterval(function () { | |
if (!functionCaller()) { | |
clearInterval(intervalFunctionCaller); | |
}; | |
}, 1000) | |
// calling a function with a click even on an html element | |
// to attach to a DOM element link to html documnet and uncomment | |
// capturing your defined Id | |
// const btn = document.getElementById("callFunc"); | |
// btn.addEventListener('click', function () { | |
// functionCaller(); | |
// }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment