Sure.
See JavaScript Scripting - Automation | openHAB for how to create and import your very own JS Scripting library. Implement your sendCommandWithRetries as a function in the library and you can import and use that where desired.
You might not need to do it all yourself though. What you describe can be implemented using LoopingTimer from openhab-rules-tools.
Using that your library function would look somthing like this (I’m just typing this in without testing, there will be typos, error checking would be needed too):
var {LoopingTimer} = require("openhab_rules_tools");
exports.sendCommandWithRetries(item, command, numRetries, delay, successFunc, failureFunc) {
var lt = cache.shared.get(ruleID+item+"Timer");
if(lt != null) lt.timer.cancel();
cache.shared.put(ruleID+item+"NumTries", 0);
lt = LoopingTimer();
items[item].sendCommand(item);
lt.loop(() => {
var tries = cache.shared.get(ruleID+item+"NumTries");
tries += 1;
var success = items[item].state == command;
if(success) {
successFunc();
return null;
}
if(tries >= numRetries) {
failureFunc();
return null;
}
cache.shared.put(ruleID+item+"NumTries", tries);
items[item].sendCommand(command);
return delay;
}, delay, item+"LoopingTimer");
}
LoopingTimer reschedules itself based on what the timer function returns. If null is returned the loop stops. So the above sends the command and sets up the looping timer to repeat sending the commands until the number of tries is up or the Item makes it to the desired state.