Is there any way to run my function within 5 seconds in Javascript?
For example if I have Function A and Function B. I want to run Function A for 5 seconds, just after it, it will run Function B.
- IF
Function Aonly takes 1 second to finish the process, then it only need to wait another 4 seconds. - But if
Function Atakes 3 seconds to finish, then it would need another 2 seconds to wait, before processingFunction B - IF
Function Atakes more than 5 seconds, then B needs to wait until A finish its job, until it can start its job. (edited)
Right now, im using Sleep Function that I found not long time ago
function wait(ms){ var start = new Date().getTime(); var end = start; while(end < start + ms) { end = new Date().getTime(); } } wait(5000); But with this code, it will need to wait for 5 seconds no matter how much time Function A needs to finish its process.
EDIT
Function A does an AJAX POST call. which makes it takes different time to finish its job.
This question is different from What is the JavaScript version of sleep()? because :
- this is going to be used in IE which doesn't support promise (as I read)
- If I use settimeout, and A takes longer than 5 seconds, then B will fire it function first without waiting A to finish.
Function Ais AjaxPOSTcall, which makes it finish the job in different time, depends on the process.