-
-
Save Slicertje/1323561 to your computer and use it in GitHub Desktop.
Detect if callback is called - async version
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
function doTest (callback, asyncTimeout) { | |
var isCallbackCalled = false; | |
var timedOut = false; | |
var timer = null; | |
var successCallback = function () { | |
if (! timedOut) { // If code success but fail already reported, keep failed | |
alert('Callback called'); | |
isCallbackCalled = true; | |
if (asyncTimeout && timer) { | |
clearTimeout(timer); | |
} | |
} | |
}; | |
callback.apply(null, [ successCallback ]); | |
if (asyncTimeout && ! isCallbackCalled) { | |
timer = setTimeout(function() { | |
alert('Callback not called!'); | |
timedOut = true; | |
}, asyncTimeout); | |
} | |
else { | |
if (! isCallbackCalled) { | |
alert('Callback not called'); | |
} | |
} | |
} | |
doTest(function (callback) { | |
alert('Test 1, callback called!'); | |
setTimeout(callback, 100); | |
}, 200); | |
doTest(function(callback) { | |
alert('Test 2, callback not called'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment