How to wait (for 2 seconds) after the completion of function? - javascript

I have javascript function which executes and after the execution i want to wait for 2 seconds. Is it possible in Javascript or not.
My Question is different. I want to wait after function gets executed or completed its execution not for till the function executes.
Javascript function
function ajax_closeCall(onDone) {
// alert("Close Call invoked.");
closeCall_onDone = onDone;
var closeCallUrl = soapUrl + "?action=closeCall&parentSessionId=" + parentSessionId;
closeCall_http_request = getNewHttpRequest('text/plain');
closeCall_http_request.onreadystatechange = callback_ajax_closeCall;
// http_request.open("POST", soapUrl, true);
closeCall_http_request.open("GET", closeCallUrl, true);
closeCall_http_request.send(null);
}
function callback_ajax_closeCall() {
if (closeCall_http_request.readyState != 4) {
return;
}
if (closeCall_http_request.status == 200) {
if (closeCall_onDone) {
closeCall_onDone();
}
stopMonitorCallState();
ajax_getCallState();
} else {
// there was a problem with the request,
// for example the response may be a 404 (Not Found)
// or 500 (Internal Server Error) response codes
alert(getLabel("cmmm_error_closecallfailed"));
}
}
After the above function executes, wait for 2 seconds.
How to achieve this scenario.

You wrap the code in a setTimeout:
setTimeout(function() {
// do your thing!
}, 2000);

you can use setInterval
setInterval(function(){
// write down your function that would you want to call after 2 seconds
}, 2000);

setTimeout gives you asynchronous wait time. for a function.
If you want to halt everything for two second. You can use the following trivial solution :
var date = new Date();var i;
for (i = date.getTime(); i<= date.getTime() + 2000; i = (new Date()).getTime()){/*Do Nothing*/}

Try this
call a function and then setTimeOut
function someFunction() //caller
{
one(); //call function one which will call second function from it
setTimeout(function()
{
//wait for 2 secs, do nothing
}, 2000);
}
// two functions after which you want to wait for 2 secs
function one()
{
two(); //it will call the second function
}
function two()
{
}

there is setTimeout function
setTimeout(function,milliseconds,param1,param2,...)
and you could use also setInterval function also
setInterval(function, milliseconds);

Related

Using clearInterval within a function to clear a setInterval on another function

I think im missing something fairly obvious with how the clearInterval method works.
So with the code below. I would expect the first function call to execute testFunction and set the interval to repeat the function. The 2nd call would execute the second function which will remove the interval from the 1st function. As this would execute far before the 5000ms interval the first function would not be executed again. However it does not behave like this.
Could someone please explain what is wrong with my method?
Reason for this is in a program I am writing I am making repeated get requests, every 30 seconds or so , using setTimeout but i would like a method to easily remove this interval at other points in the program
function testFunction() {
$("#test").append("test");
setTimeout(testFunction, 5000);
}
function stopFunction() {
clearTimeout(testFunction);
}
testFunction();
stopFunction();
setTimeout returns an ID so you should
var timeoutID = setTimeout(blah blah);
clearTimeout(timeoutID);
setTimeout returns an object that you need to pass into the clearTimeout method. See this article for an example: http://www.w3schools.com/jsref/met_win_cleartimeout.asp
setTimeout returns an identifier for the timer. Store this in a variable like:
var timeout;
function testFunction(){
...
timeout = setTimeout(testFunction, 5000);
}
function stopFunction(){
clearTimeout(timeout);
}
Here is a simple and I think better implementation for this .
var _timer = null,
_interval = 5000,
inProgress = false,
failures = 0,
MAX_FAILURES = 3;
function _update() {
// do request here, call _onResolve if no errors , and _onReject if errors
}
function _start() {
inProgress = true;
_update();
_timer = setInterval(_update, _interval);
}
function _end() {
inProgress = false;
clearInterval(_timer);
}
function _onReject(err) {
if (failures >= MAX_FAILURES) {
_end();
return false;
}
_end();
failures++;
_start();
}
function _onResolve(response) {
return true;
}

javascript wait specific amount of time before executing a function

is there any way to delay a function in javascript I want to do such thing:
function showLabel(){
document.getElementById(id).show();
wait(5000); //wait 5 sec
document.getElementById(id).hide();
}
I want to show a label for 5 sec if this function is called, there may be another way to do so.
Note: I can't use jQuery
Hint: Use setTimeout
window.setTimeout("javascript function", milliseconds);
Read the docs and find out how to do it: https://developer.mozilla.org/en/docs/Web/API/window.setTimeout
If you want something like sleep then:
function sleep(millis, callback) {
setTimeout(function()
{ callback(); }
, milliseconds);
}
I'd prefer:
function doStuff()
{
//do some things
setTimeout(continueExecution, 10000) //wait ten seconds before continuing
}
function continueExecution()
{
//finish doing things after the pause
}
Another way using loop
<script type="text/javascript">
// bad implementation
function sleep(milliSeconds){
var startTime = new Date().getTime(); // get the current time
while (new Date().getTime() < startTime + milliSeconds); // hog cpu
}
</script>
You may try this:
function showLabel(){
document.getElementById(id).show();
setTimeout(function()
{
document.getElementById(id).hide();
}, 5000);
}
Use setTimeout for one time task, else setInterval for repetitive task.
use setTimeout function in javascript. and clear the time out one the function call over
var timerId = setTimeout(function showLabel(){
document.getElementById(id).show();
document.getElementById(id).hide();
}, 5000);
clearTimeout(timerId);
setTimeout(
function(){ Your_function }, milliseconds
);
This calls the function after the given time is up.

Wait for Function to complete and then return a value

I have this function Offline.check(); , which takes 1 seconds to execute..So below function is not waiting for it and it always return false on first time.I used set time out..but thats always returning null.
function checkstats()
{
Offline.check(); // This returns Offline.state=up or down and it takes 1 seconds to complete.
if(Offline.state=="up")
{
return true;
}
else
{
return false;
}
}
var a = checkstats();
Ideally you could set a callback function with Offline.check, but I understand it is external, so that won't work.
You can use a timeout to wait for Offline.state to get set, but then you'll need to do any actions involving the variable a asynchronously too:
function checkstats(callBack){ // checkstats() now takes a callback
Offline.check(); // Start Offline.check() as usual
setTimeout(function(){ // Set a timeout for 1 second
if(Offline.state=="up") // After 1 second, check Offline.state as usual
{
callBack(true); // ...but we call the callback instead of returning
}
else
{
callBack(false); // ...but we call the callback instead of returning
}
}, 1000);
}
checkstats(function(a){ // This anonymous function is the callback we're using
// Now you can use "a" normally
});
If you're not sure that Offline.check() will take exactly 1 second, you can use an interval instead of a timeout, and try every second for, say, 5 seconds:
function checkstats(callBack){
Offline.check();
var attempt = 0, maxAttempts = 5;
var checkStatsInterval = setInterval(function(){
if(++attempt > maxAttempts){
// Ran out of attempts, just give up
clearInterval(checkStatsInterval);
alert('Waited '+maxAttempts+' seconds for Offline data. Giving up!');
return;
}
if(Offline.state){
clearInterval(checkStatsInterval);
// It's loaded! Now confidently check Offline.state
if(Offline.state=="up")
{
callBack(true);
}
else
{
callBack(false);
}
}
}, 1000);
}
checkstats(function(a){
// Now you can use "a" normally
});
You can use Asynchronous JavaScript to address the issue. There are several ways of implementing asynchronous behaviour in JavaScript. You can use Callbacks, Listeners or Promises.
Anyway, if you are certain that it only takes 1 second, setTimeout in a callback function and allow Offline.check() to complete. (If it's external or lazy to implement async there)
doOfflineCheck(function(){
if(Offline.state=="up")
{
return true;
}
else
{
return false;
}
});
function doOfflineCheck(cb){
setTimeout(function(){
Offline.check();
},1000);
}

setTimeout and setInterval not working

I want to be able to call the function work() every 6 seconds. My jQuery code is
function looper(){
// do something
if (loopcheck) {
setInterval(work,6000);
}
else {
console.log('looper stopped');
}
}
The problem I am running into is that it loops over work twice quickly, and then it will wait for 6 seconds. i tried using setTimeout with similar results.
What could be causing work to be called twice before the delay works?
setInterval should be avoided. If you want work to be repeatedly called every 6 seconds, consider a recursive call to setTimeout instead
function loopWork(){
setTimeout(function () {
work();
loopWork();
}, 6000);
}
Then
function looper(){
// do something
if (loopcheck) {
loopWork()
}
else {
console.log('looper stopped');
}
}
And of course if you ever want to stop this, you'd save the value of the last call to setTimeout, and pass that to clearTimeout
var timeoutId;
timeoutId = setTimeout(function () {
work();
loopWork();
}, 6000);
Then to stop it
clearTimeout(timeoutId);
Use old-style setTimeout()
var i=0;
function work(){
console.log(i++);
}
function runner(){
work();
setTimeout(runner, 6000);
}
runner();
I prefer the following pattern myself I find it easier to follow:
function LoopingFunction() {
// do the work
setTimeout(arguments.callee, 6000); // call myself again in 6 seconds
}
And if you want to be able to stop it at any point:
var LoopingFunctionKeepGoing = true;
function LoopingFunction() {
if(!LoopingFunctionKeepGoing) return;
// do the work
setTimeout(arguments.callee, 6000); // call myself again in 6 seconds
}
Now you can stop it at any time by setting LoopingFunctionKeepGoing to false.

Implementing timeouts for node.js callbacks

This is a typical situation in node.js:
asyncFunction(arguments, callback);
When asynFunction completes, callback gets called. A problem I see with this pattern is that, if asyncFunction never completes (and asynFunction doesn't have a built-in time-out system) then callback will never be called. Worse, it seems that callback has no way of determining that asynFunction will never return.
I want to implement a "timeout" whereby if callback has not been called by asyncFunction within 1 second, then callback automatically gets called with the assumption that asynFunction has errored out. What is the standard way of doing this?
I'm not familiar with any libraries that do this, but it's not hard to wire up yourself.
// Setup the timeout handler
var timeoutProtect = setTimeout(function() {
// Clear the local timer variable, indicating the timeout has been triggered.
timeoutProtect = null;
// Execute the callback with an error argument.
callback({error:'async timed out'});
}, 5000);
// Call the async function
asyncFunction(arguments, function() {
// Proceed only if the timeout handler has not yet fired.
if (timeoutProtect) {
// Clear the scheduled timeout handler
clearTimeout(timeoutProtect);
// Run the real callback.
callback();
}
});
You probably need to come out with a solution of your own. Like
function callBackWithATimeout (callback, timeout) {
var run, timer;
run = function () {
if (timer) {
clearTimeout(timer);
timer = null;
callback.apply(this, arguments);
}
};
timer = setTimeout(run, timeout, "timeout");
return run;
}
and then
asyncFunction(arguments, callBackWithATimeout(callback, 2000));
You could do something like this:
function ensureExecution(func, timeout) {
var timer, run, called = false;
run = function() {
if(!called) {
clearTimeout(timer);
called = true;
func.apply(this, arguments);
}
};
timer = setTimeout(run, timeout);
return run;
}
Usage:
asyncFunction(arguments, ensureExecution(callback, 1000));
DEMO
But note the following:
The timeout is started immediately when you call ensureExecution, so you cannot cache that function reference.
The arguments passed to the callback will differ. For example asyncFunction might pass some arguments to callback upon success, but if the function is called by the timeout, no arguments will be passed. You have to keep that it mind. You could also provide default arguments with which the function should be called in this case:
function ensureExecution(func, timeout, args, this_obj) {
// ...
timer = setTimeout(function() {
run.apply(this_obj, args);
}, timeout);
//...
}
I ran into the same problem with a content script trying to open the port on the BG extension before the BG extension was ready. A work around was to wait for the BG extension to reply to a message and repeat this till successful. Here are the code snippets.
Content Script:
var nTimes = 10;
var bIsReady = false;
checkBGReady();
function checkBGReady() {
if (!bIsReady) {
chrome.runtime.sendMessage({msgText: "hello "+nTimes}, function(response) {
if (response && response.ack) {
console.log("have response:"+response.ack+" "+nTimes);
bIsReady = true;
// continue with initialization
bootStrap(sURL);
checkReady();
} else {
console.log("have no ack response %o",response);
}
});
}
nTimes -= 1;
if (nTimes > 0 && !bIsReady) {
setTimeout(checkBGReady,100);
}
}
BG Extension
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
console.log(sender.tab ?"from a content script:" + sender.tab.url :"from the extension");
if (request.msgText) {
console.log("Have msg "+request.msgText);
sendResponse({ack: "have contact "+request.msgText});
}
});
In my case it usually took after the first 100ms delay.

Categories

Resources