Created
May 26, 2016 14:08
-
-
Save dolvik/4e2feda262bde8d64741cd39c7cbdb7e to your computer and use it in GitHub Desktop.
Limit number of function running at the same time
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta name="description" content="Call any function just once within a period of time"> | |
<meta charset="utf-8"> | |
<meta name="viewport" content="width=device-width"> | |
<title>JS Bin</title> | |
</head> | |
<body> | |
<input type="button" value="Call function 3 times" onclick="onClick()"> | |
</body> | |
</html> |
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
var period = 1000; | |
var n = 2; //max number of functions executiong within a period | |
//function decorator | |
function getFunction(context){ | |
return function(func){ | |
var running = 0; | |
return function(){ | |
if (running === n){ | |
console.log(running + " functions are running. Only " + n + " functions can run at the same time. Cancel excecution"); | |
return; | |
} | |
running++; | |
func.apply(context, arguments); | |
setTimeout(function(){ | |
running--; | |
}, period); | |
}; | |
}; | |
} | |
//function that takes much time | |
function getData(filter, callback){ | |
console.log("Call function with argument filter = " + filter); | |
setTimeout(function(){ | |
callback(null, {data: [1, 2, 3]}); | |
}, 500); | |
} | |
//create a wrapper | |
var wrapper = getFunction(this)(getData); | |
//call this function 3 times when button is clicked | |
function onClick(){ | |
var filter = "some filter"; | |
var callback = function(err, result){ | |
if (err){ | |
console.log("Error: " + err); | |
return; | |
} | |
console.log("Function is complete. Result = " + JSON.stringify(result)); | |
}; | |
wrapper(filter, callback); | |
wrapper(filter, callback); | |
wrapper(filter, callback); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment