Rectangle 27 23

You can work that out with simple math :

1000ms : 0 4000ms : 1 7000ms : 2 10000ms : 3 13000ms : 4 ...

It seem that your request is a bit blurry. if you want to do something after the last timeout, you can set a limit and compare the current index :

var limit = 10
for (var i=0;i<=limit;i++) {
   (function(ind) {
       setTimeout(function(){
           console.log(ind);
           if(ind === limit){
               console.log('It was the last one');
           }
       }, 1000 + (3000 * ind));
   })(i);
}
for (var i=0;i<=10;i++) {
   (function(ind) {
       setTimeout(function(){console.log(ind);}, 1000 * ind);
   })(i);
}

I'm not sure that's exactly what the OP wants either (although it's definitely better). I think they want to wait until all the timeouts have fired and then continue.

Maybe this doesn't matter - and it's certainly not Gagnon's fault, this is how the question presented it - but you do realize that the execution of the script is long past the for-loop even before the first console.log right? See: jsfiddle.net/WXkLK

@myfunkyside Yes i know that, but I just cant really tell what OP want...

@Karl-AndrGagnon - I know, I know, that's why I started off with clearing you of any blame

@myfunkyside fair enough, as long as my name is clear! :)

settimeout - JavaScript : For loop with timeout - Stack Overflow

javascript settimeout
Rectangle 27 9

(function fn(n) {
  console.log(n);
  if (n < 9) setTimeout(function() {
    fn(++n);
  }, 1000);
}(0));

settimeout - JavaScript : For loop with timeout - Stack Overflow

javascript settimeout
Rectangle 27 5

why not use something like this:

var i = 0
var id = window.setInterval(function(){
    if(i >= 10) {
        clearInterval(id);
        return;
    }

    console.log(i);
    i++;
}, 1000)

settimeout - JavaScript : For loop with timeout - Stack Overflow

javascript settimeout
Rectangle 27 3

function initiateTimeOut(i) {
  setTimeout(function() { doStuff(i) }, 30);
}
function doStuff(i) {
    console.log(i);
    i++;
    if (i <= 10) {
        initiateTimeOut(i); 
    }
}

initiateTimeOut(0);

this way you will only increment i when your function executes, which i believe is what your looking for.

Example in a fiddle: http://jsfiddle.net/My7Zg/

function customLoop(i) {
    console.log(i);
    i++;
    if (i<=10) {setTimeout(function(){customLoop(i);},1000);}
}
customLoop(0);

Wouldn't that give a stack error?

1) I doubt this works as you think, 2) this is not what the OP wanted.

Yep, this is BAD. Please revise or remove.

settimeout - JavaScript : For loop with timeout - Stack Overflow

javascript settimeout
Rectangle 27 5

setTimeout('',1)

This line does absolutely nothing. You are telling JavaScript to eval() the string ''. That does nothing.

Sometimes doing this is useful, as it "pushes the code to the bottom of the stack" to run it after the function (and whatever UI updates the browser is doing) finishes.

setTimeout(function(){
    // Work with some DOM elements, after the browser has a second to render them
}, 0);

But I can't see an empty string having any effect on anything.

EDIT: In Google Chrome, if you do setTimeout('',1) it doesn't return you anything. Normally, it would return you the timeout_id, so you could cancel it with clearTimeout. But, in Google Chrome, setTimeout('',1) returns undefined, which makes be believe it doesn't even set a timeout, since you didn't give it anything to do. So, yeah, it literally does absolutely nothing.

Why a down-vote? Am I wrong? Does setTimeout('',1) (or eval('')) actually do anything? I can't think of this actually having any effect (good or bad) on anything.

I have no idea why someone down voted this. It's a perfectly correct answer.

settimeout - "Stray timeout" - what does the empty timeout in javascri...

javascript settimeout
Rectangle 27 24

// Using jQuery (but could use pure JS with cross-browser event handlers):
var idleSeconds = 30;

$(function(){
  var idleTimer;
  function resetTimer(){
    clearTimeout(idleTimer);
    idleTimer = setTimeout(whenUserIdle,idleSeconds*1000);
  }
  $(document.body).bind('mousemove keydown click',resetTimer); //space separated events list that we want to monitor
  resetTimer(); // Start the timer when the page loads
});

function whenUserIdle(){
  //...
}

Edit: Not using jQuery for whatever reason? Here's some (untested) code that should be cross-browser clean (to a point; doesn't work on IE5 Mac, for example ;):

attachEvent(window,'load',function(){
  var idleSeconds = 30;
  var idleTimer;
  function resetTimer(){
    clearTimeout(idleTimer);
    idleTimer = setTimeout(whenUserIdle,idleSeconds*1000);
  }
  attachEvent(document.body,'mousemove',resetTimer);
  attachEvent(document.body,'keydown',resetTimer);
  attachEvent(document.body,'click',resetTimer);

  resetTimer(); // Start the timer when the page loads
});

function whenUserIdle(){
  //...
}

function attachEvent(obj,evt,fnc,useCapture){
  if (obj.addEventListener){
    obj.addEventListener(evt,fnc,!!useCapture);
    return true;
  } else if (obj.attachEvent){
    return obj.attachEvent("on"+evt,fnc);
  }
}

Thanks for quick answer, but I'm looking for pure JS.

This was very helpful, thanks! In the jquery version, for me the comma-delimited list of events did not work. I had to use spaces.

You are adorable! You've just put an end to my 2-day fruitless research. I am working on a canvas image slider with createJS, and wanted an "autoslide" function when the user is not doing anything, and then halt the "autoslide" when the user clicks on something. This works perfect for me! Here's one vote up for you.

Javascript timeout when no actions from user for specified time - Stac...

javascript timeout
Rectangle 27 24

// Using jQuery (but could use pure JS with cross-browser event handlers):
var idleSeconds = 30;

$(function(){
  var idleTimer;
  function resetTimer(){
    clearTimeout(idleTimer);
    idleTimer = setTimeout(whenUserIdle,idleSeconds*1000);
  }
  $(document.body).bind('mousemove keydown click',resetTimer); //space separated events list that we want to monitor
  resetTimer(); // Start the timer when the page loads
});

function whenUserIdle(){
  //...
}

Edit: Not using jQuery for whatever reason? Here's some (untested) code that should be cross-browser clean (to a point; doesn't work on IE5 Mac, for example ;):

attachEvent(window,'load',function(){
  var idleSeconds = 30;
  var idleTimer;
  function resetTimer(){
    clearTimeout(idleTimer);
    idleTimer = setTimeout(whenUserIdle,idleSeconds*1000);
  }
  attachEvent(document.body,'mousemove',resetTimer);
  attachEvent(document.body,'keydown',resetTimer);
  attachEvent(document.body,'click',resetTimer);

  resetTimer(); // Start the timer when the page loads
});

function whenUserIdle(){
  //...
}

function attachEvent(obj,evt,fnc,useCapture){
  if (obj.addEventListener){
    obj.addEventListener(evt,fnc,!!useCapture);
    return true;
  } else if (obj.attachEvent){
    return obj.attachEvent("on"+evt,fnc);
  }
}

Thanks for quick answer, but I'm looking for pure JS.

This was very helpful, thanks! In the jquery version, for me the comma-delimited list of events did not work. I had to use spaces.

You are adorable! You've just put an end to my 2-day fruitless research. I am working on a canvas image slider with createJS, and wanted an "autoslide" function when the user is not doing anything, and then halt the "autoslide" when the user clicks on something. This works perfect for me! Here's one vote up for you.

Javascript timeout when no actions from user for specified time - Stac...

javascript timeout
Rectangle 27 10

function MouseDownEvent(e) {
    *snip*
    timeoutID = setTimeout(function(){checkPos(e);}, 500);
}
function checkPos(e) {
    //function uses e on a timeout of 500ms
}
var myNamespace = {};

$('body').mousemove(function(e) {
    myNamespace.mouseEvent = e; 
});

function checkPos() {
    doSomethingWith(myNamespace.mouseEvent);
}

timerID = setInterval(checkPos, 500);

Sorry to back off on this answer, but when I re-ran this code putting checkPos(e); in, it failed to bring in the updated e event after each timeout.

It won't work with your edited code. This method forms a 'closure' over e. To access an updated event, you need to store the event somewhere that is accessible to the checkPos function (external to it), and update that stored event in the MouseDownEvent function.

There's no way to call the event object in javascript or jQuery such that I can pull in the current mouse position based on the timeout?

@C Bauer perhaps it would help if you explained why you need to use a timeout. Javascript has a MouseMove event for polling the mouse position, so I don't see why you'd want to use a timeout. See my answer for more.

jquery - Javascript setTimeout function call with event argument? - St...

javascript jquery settimeout
Rectangle 27 1455

Reading State in Thunks

Dont fall into the trap of thinking a library should prescribe how to do everything. If you want to do something with a timeout in JavaScript, you need to use setTimeout. There is no reason why Redux actions should be any different.

Redux does offer some alternative ways of dealing with asynchronous stuff, but you should only use those when you realize you are repeating too much code. Unless you have this problem, use what the language offers and go for the simplest solution.

This is by far the simplest way. And theres nothing specific to Redux here.

Similarly, from inside a connected component:

this.props.dispatch({ type: 'SHOW_NOTIFICATION', text: 'You logged in.' })
setTimeout(() => {
  this.props.dispatch({ type: 'HIDE_NOTIFICATION' })
}, 5000)

The only difference is that in a connected component you usually dont have access to the store itself, but get either dispatch() or specific action creators injected as props. However this doesnt make any difference for us.

If you dont like making typos when dispatching the same actions from different components, you might want to extract action creators instead of dispatching action objects inline:

// actions.js
export function showNotification(text) {
  return { type: 'SHOW_NOTIFICATION', text }
}
export function hideNotification() {
  return { type: 'HIDE_NOTIFICATION' }
}

// component.js
import { showNotification, hideNotification } from '../actions'

this.props.dispatch(showNotification('You just logged in.'))
setTimeout(() => {
  this.props.dispatch(hideNotification())
}, 5000)

Or, if you have previously bound them with connect():

this.props.showNotification('You just logged in.')
setTimeout(() => {
  this.props.hideNotification()
}, 5000)

So far we have not used any middleware or other advanced concept.

The approach above works fine in simple cases but you might find that it has a few problems:

  • It forces you to duplicate this logic anywhere you want to show a notification.
  • The notifications have no IDs so youll have a race condition if you show two notifications fast enough. When the first timeout finishes, it will dispatch HIDE_NOTIFICATION, erroneously hiding the second notification sooner than after the timeout.

To solve these problems, you would need to extract a function that centralizes the timeout logic and dispatches those two actions. It might look like this:

// actions.js
function showNotification(id, text) {
  return { type: 'SHOW_NOTIFICATION', id, text }
}
function hideNotification(id) {
  return { type: 'HIDE_NOTIFICATION', id }
}

let nextNotificationId = 0
export function showNotificationWithTimeout(dispatch, text) {
  // Assigning IDs to notifications lets reducer ignore HIDE_NOTIFICATION
  // for the notification that is not currently visible.
  // Alternatively, we could store the interval ID and call
  // clearInterval(), but wed still want to do it in a single place.
  const id = nextNotificationId++
  dispatch(showNotification(id, text))

  setTimeout(() => {
    dispatch(hideNotification(id))
  }, 5000)
}

Now components can use showNotificationWithTimeout without duplicating this logic or having race conditions with different notifications:

Why does showNotificationWithTimeout() accept dispatch as the first argument? Because it needs to dispatch actions to the store. Normally a component has access to dispatch but since we want an external function to take control over dispatching, we need to give it control over dispatching.

If you had a singleton store exported from some module, you could just import it and dispatch directly on it instead:

// store.js
export default createStore(reducer)

// actions.js
import store from './store'

// ...

let nextNotificationId = 0
export function showNotificationWithTimeout(text) {
  const id = nextNotificationId++
  store.dispatch(showNotification(id, text))

  setTimeout(() => {
    store.dispatch(hideNotification(id))
  }, 5000)
}

// component.js
showNotificationWithTimeout('You just logged in.')

// otherComponent.js
showNotificationWithTimeout('You just logged out.')

This looks simpler but we dont recommend this approach. The main reason we dislike it is because it forces store to be a singleton. This makes it very hard to implement server rendering. On the server, you will want each request to have its own store, so that different users get different preloaded data.

A singleton store also makes testing harder. You can no longer mock a store when testing action creators because they reference a specific real store exported from a specific module. You cant even reset its state from outside.

So while you technically can export a singleton store from a module, we discourage it. Dont do this unless you are sure that your app will never add server rendering.

// actions.js

// ...

let nextNotificationId = 0
export function showNotificationWithTimeout(dispatch, text) {
  const id = nextNotificationId++
  dispatch(showNotification(id, text))

  setTimeout(() => {
    dispatch(hideNotification(id))
  }, 5000)
}

// component.js
showNotificationWithTimeout(this.props.dispatch, 'You just logged in.')

// otherComponent.js
showNotificationWithTimeout(this.props.dispatch, 'You just logged out.')

This solves the problems with duplication of logic and saves us from race conditions.

For simple apps, the approach should suffice. Dont worry about middleware if youre happy with it.

For example, it seems unfortunate that we have to pass dispatch around. This makes it trickier to separate container and presentational components because any component that dispatches Redux actions asynchronously in the manner above has to accept dispatch as a prop so it can pass it further. You cant just bind action creators with connect() anymore because showNotificationWithTimeout() is not really an action creator. It does not return a Redux action.

In addition, it can be awkward to remember which functions are synchronous action creators like showNotification() and which are asynchronous helpers like showNotificationWithTimeout(). You have to use them differently and be careful not to mistake them with each other.

finding a way to legitimize this pattern of providing dispatch to a helper function, and help Redux see such asynchronous action creators as a special case of normal action creators

If youre still with us and you also recognize as a problem in your app, you are welcome to use the Redux Thunk middleware.

In a gist, Redux Thunk teaches Redux to recognize special kinds of actions that are in fact functions:

import { createStore, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'

const store = createStore(
  reducer,
  applyMiddleware(thunk)
)

// It still recognizes plain object actions
store.dispatch({ type: 'INCREMENT' })

// But with thunk middleware, it also recognizes functions
store.dispatch(function (dispatch) {
  // ... which themselves may dispatch many times
  dispatch({ type: 'INCREMENT' })
  dispatch({ type: 'INCREMENT' })
  dispatch({ type: 'INCREMENT' })

  setTimeout(() => {
    // ... even asynchronously!
    dispatch({ type: 'DECREMENT' })
  }, 1000)
})

When this middleware is enabled, if you dispatch a function, Redux Thunk middleware will give it dispatch as an argument. It will also swallow such actions so dont worry about your reducers receiving weird function arguments. Your reducers will only receive plain object actionseither emitted directly, or emitted by the functions as we just described.

This does not look very useful, does it? Not in this particular situation. However it lets us declare showNotificationWithTimeout() as a regular Redux action creator:

// actions.js
function showNotification(id, text) {
  return { type: 'SHOW_NOTIFICATION', id, text }
}
function hideNotification(id) {
  return { type: 'HIDE_NOTIFICATION', id }
}

let nextNotificationId = 0
export function showNotificationWithTimeout(text) {
  return function (dispatch) {
    const id = nextNotificationId++
    dispatch(showNotification(id, text))

    setTimeout(() => {
      dispatch(hideNotification(id))
    }, 5000)
  }
}

Note how the function is almost identical to the one we wrote in the previous section. However it doesnt accept dispatch as the first argument. Instead it returns a function that accepts dispatch as the first argument.

How would we use it in our component? Definitely, we could write this:

// component.js
showNotificationWithTimeout('You just logged in.')(this.props.dispatch)

We are calling the async action creator to get the inner function that wants just dispatch, and then we pass dispatch.

However this is even more awkward than the original version! Why did we even go that way?

If Redux Thunk middleware is enabled, any time you attempt to dispatch a function instead of an action object, the middleware will call that function with dispatch method itself as the first argument

So we can do this instead:

// component.js
this.props.dispatch(showNotificationWithTimeout('You just logged in.'))

Finally, dispatching an asynchronous action (really, a series of actions) looks no different than dispatching a single action synchronously to the component. Which is good because components shouldnt care whether something happens synchronously or asynchronously. We just abstracted that away.

Notice that since we taught Redux to recognize such special action creators (we call them thunk action creators), we can now use them in any place where we would use regular action creators. For example, we can use them with connect():

// actions.js

function showNotification(id, text) {
  return { type: 'SHOW_NOTIFICATION', id, text }
}
function hideNotification(id) {
  return { type: 'HIDE_NOTIFICATION', id }
}

let nextNotificationId = 0
export function showNotificationWithTimeout(text) {
  return function (dispatch) {
    const id = nextNotificationId++
    dispatch(showNotification(id, text))

    setTimeout(() => {
      dispatch(hideNotification(id))
    }, 5000)
  }
}

// component.js

import { connect } from 'react-redux'

// ...

this.props.showNotificationWithTimeout('You just logged in.')

// ...

export default connect(
  mapStateToProps,
  { showNotificationWithTimeout }
)(MyComponent)

Usually your reducers contain the business logic for determining the next state. However, reducers only kick in after the actions are dispatched. What if you have a side effect (such as calling an API) in a thunk action creator, and you want to prevent it under some condition?

Without using the thunk middleware, youd just do this check inside the component:

// component.js
if (this.props.areNotificationsEnabled) {
  showNotificationWithTimeout(this.props.dispatch, 'You just logged in.')
}

However, the point of extracting an action creator was to centralize this repetitive logic across many components. Fortunately, Redux Thunk offers you a way to read the current state of the Redux store. In addition to dispatch, it also passes getState as the second argument to the function you return from your thunk action creator. This lets the thunk read the current state of the store.

let nextNotificationId = 0
export function showNotificationWithTimeout(text) {
  return function (dispatch, getState) {
    // Unlike in a regular action creator, we can exit early in a thunk
    // Redux doesnt care about its return value (or lack of it)
    if (!getState().areNotificationsEnabled) {
      return
    }

    const id = nextNotificationId++
    dispatch(showNotification(id, text))

    setTimeout(() => {
      dispatch(hideNotification(id))
    }, 5000)
  }
}

Dont abuse this pattern. It is good for bailing out of API calls when there is cached data available, but it is not a very good foundation to build your business logic upon. If you use getState() only to conditionally dispatch different actions, consider putting the business logic into the reducers instead.

Now that you have a basic intuition about how thunks work, check out Redux async example which uses them.

You may find many examples in which thunks return Promises. This is not required but can be very convenient. Redux doesnt care what you return from a thunk, but it gives you its return value from dispatch(). This is why you can return a Promise from a thunk and wait for it to complete by calling dispatch(someThunkReturningPromise()).then(...).

You may also split complex thunk action creators into several smaller thunk action creators. The dispatch method provided by thunks can accept thunks itself, so you can apply the pattern recursively. Again, this works best with Promises because you can implement asynchronous control flow on top of that.

For some apps, you may find yourself in a situation where your asynchronous control flow requirements are too complex to be expressed with thunks. For example, retrying failed requests, reauthorization flow with tokens, or a step-by-step onboarding can be too verbose and error-prone when written this way. In this case, you might want to look at more advanced asynchronous control flow solutions such as Redux Saga or Redux Loop. Evaluate them, compare the examples relevant to your needs, and pick the one you like the most.

Finally, dont use anything (including thunks) if you dont have the genuine need for them. Remember that, depending on the requirements, your solution might look as simple as

store.dispatch({ type: 'SHOW_NOTIFICATION', text: 'You logged in.' })
setTimeout(() => {
  store.dispatch({ type: 'HIDE_NOTIFICATION' })
}, 5000)

Dont sweat it unless you know why youre doing this.

Async actions seem like such a simple and elegant solution to a common problem. Why isn't support for them baked in to redux without the need for middleware? This answer could then be so much more concise.

@PhilMander Because there are many alternative patterns like github.com/raisemarketplace/redux-loop or github.com/yelouafi/redux-saga which are just as (if not more) elegant. Redux is a low-level tool. You can build a superset you like and distribute it separately.

Can you explain this: *consider putting the business logic into the reducers *, does that mean I should dispatch an action, and then determine in the reducer what further actions to dispatch depending on my state? My question is, do I then dispatch other actions directly in my reducer, and if not then where do I dispatch them from?

if (cond) dispatch({ type: 'A' }) else dispatch({ type: 'B' })
dispatch({ type: 'C', something: cond })
action.something

@DanAbramov You got my upvote just for this "Unless you have this problem, use what the language offers and go for the simplest solution." Only after did I realise who wrote it!

javascript - How to dispatch a Redux action with a timeout? - Stack Ov...

javascript timeout redux
Rectangle 27 7

Firstly why are you using two timeouts? It looks to me like setInterval() would be better

function MouseDownEvent(e) {
 *snip*
 clearInterval(intervalID);
 intervalID = setInterval(function(){checkPos(e);}, 500);
}

Secondly could you please clarify this : "...but never updates the e object as the user moves the mouse." Why would the event object be updated when the user moves the mouse? You've only assigned a mouseDown handler. If you wanted to do something on every mouse move then you should use a mouseMove event, in which case the timeout / interval would be unnecessary anyway.

function MouseMoveEvent(e) {
 //called every time the mouse is moved, event object will contain position
}

As always in JavaScript you should look for an event driven solution first and only use timed handlers when you absolutely have to.

*Edit - addressing issues op raised in comments *

var handler = {
    i : 0,
    function : mouseMoveEvent(e) {
      handler.i++;
      if (handler.i % 100 == 0) {
        //Do expensive operations
      }
    }
}

$(myElement).bind("mousemove", handler.mouseMoveEvent);

jquery - Javascript setTimeout function call with event argument? - St...

javascript jquery settimeout
Rectangle 27 275

setTimeout(expression, timeout);

setInterval(expression, timeout); runs the code/function in intervals, with the length of the timeout between them.

var intervalID = setInterval(alert, 1000); // Will alert every second.
// clearInterval(intervalID); // Will clear the timer.

setTimeout(alert, 1000); // Will alert once, after a second.

I have a div I want to display once the page loads and fade away after X seconds. Would using setTimeout with a function which changes the style to display none accomplish this?

if the page refresh then set interval is also reset or not?

@lunixbochs, can you say, does setInterval or setTimeout also refreshed when page refreshed?

javascript - 'setInterval' vs 'setTimeout' - Stack Overflow

javascript
Rectangle 27 3

setTimeout( this.f.bind(this), 60000 );

Never pass a string to setTimeout as it will be evaluated in global context.

Afaik, bind is not IE6-8 compatible.

@Oleg The code is for a firefox extension, and even if it wasn't you can make the used subset of bind in 3 lines of code.

firefox addon - sleep in Javascript via timeout - Stack Overflow

javascript firefox-addon timeout sleep wait
Rectangle 27 2

One possibility is that it is a browser version test.

setTimeout('',1)
undefined

This is possible, but what exactly is it testing for? You got undefined... now what? Is it Chrome? IE9? This is a good theory, though it's a bad way to implement a browser check. +1 though for the theory.

Agreed, this would be quite an incomplete test if this were it. That's why I upvoted Bergi's question about how t is used.

settimeout - "Stray timeout" - what does the empty timeout in javascri...

javascript settimeout
Rectangle 27 117

You can create a setTimeout loop using recursion:

function timeout() {
    setTimeout(function () {
        // Do Something Here
        // Then recall the parent function to
        // create a recursive loop.
        timeout();
    }, 1000);
}

The problem with setInterval() and setTimeout() is that there is no guarantee your code will run in the specified time. By using setTimeout() and calling it recursively, you're ensuring that all previous operations inside the timeout are complete before the next iteration of the code begins.

What's the difference between this method and using setInterval?

the issue with this approach is that if the function takes longer than 1000ms to complete, it all goes belly up. this isnt guaranteed to execute every 1000ms. setInterval is.

@TJC: That very much depends on exactly what you are trying to achieve. It might be more important that the previous function complete before the next iteration, or maybe not.

@TJC Correct, but if your previous operations are not complete before setInterval() re-executes, your variables and/or data could get out of sync really fast. If I'm ajaxing for data for example, and the server takes longer than 1 sec to respond, using setInterval() my previous data would not have finished processing before my next operation continued. With this approach, it's not guaranteed that your function will kick off every second. However, it is guaranteed that your previous data will have finished processing before the next interval kicks off.

@War10ck, given a music based environment, I assumed that it was not going to be used to set variables or ajax calls where order mattered.

Javascript, setTimeout loops? - Stack Overflow

javascript settimeout setinterval timing
Rectangle 27 42

Just for the record, there is a way to get the time left in node.js:

var timeout = setTimeout(function() {}, 3600 * 1000);

setInterval(function() {
    console.log('Time left: '+getTimeLeft(timeout)+'s');
}, 2000);

function getTimeLeft(timeout) {
    return Math.ceil((timeout._idleStart + timeout._idleTimeout - Date.now()) / 1000);
}
$ node test.js 
Time left: 3599s
Time left: 3597s
Time left: 3595s
Time left: 3593s

This doesn't seem to work in firefox through, but since node.js is javascript, I thought this remark might be helpful for people looking for the node solution.

not sure if it's new version of node or what but in order for this to work i had to remove "getTime()" part. it seems _idleStart is already an integer now

I have just tried it in node 0.10, getTime() is removed, _idleStart is already the time

not work on node 6.3, because the timeout structure is leak of those information.

javascript - find the time left in a setTimeout()? - Stack Overflow

javascript timeout settimeout
Rectangle 27 36

function timer(callback, delay) {
    var id, started, remaining = delay, running

    this.start = function() {
        running = true
        started = new Date()
        id = setTimeout(callback, remaining)
    }

    this.pause = function() {
        running = false
        clearTimeout(id)
        remaining -= new Date() - started
    }

    this.getTimeLeft = function() {
        if (running) {
            this.pause()
            this.start()
        }

        return remaining
    }

    this.getStateRunning = function() {
        return running
    }

    this.start()
}

Make a timer:

a = new timer(function() {
    // What ever
}, 3000)

So if you want the time remaining just do:

a.getTimeLeft()

Thanks for that. Not exactly what I've been looking for, but function to count time left is very useful

Nice and elegant.

javascript - find the time left in a setTimeout()? - Stack Overflow

javascript timeout settimeout
Rectangle 27 27

Looks like Javascript execution is paused on MobileSafari when the browser page isn't focused. It also seems if setInterval() events are late, they are simply fired as soon as the browser is focused. This means we should be able to keep a setInterval() running, and assume the browser lost/regained focus if the setInterval function took much longer than usual.

This code alerts after switching back from a browser tab, after switching back from another app, and after resuming from sleep. If you set your threshold a bit longer than your setTimeout(), you can assume your timeout wouldn't finish if this fires.

If you wanted to stay on the safe side: you could save your timeout ID (returned by setTimeout) and set this to a shorter threshold than your timeout, then run clearTimeout() and setTimeout() again if this fires.

<script type="text/javascript">
var lastCheck = 0;

function sleepCheck() {
        var now = new Date().getTime();
        var diff = now - lastCheck;
        if (diff > 3000) {
                alert('took ' + diff + 'ms');
        }
        lastCheck = now;
}

window.onload = function() {
        lastCheck = new Date().getTime();
        setInterval(sleepCheck, 1000);
}
</script>

Edit: It appears this can sometimes trigger more than once in a row on resume, so you'd need to handle that somehow. (After letting my android browser sleep all night, it woke up to two alert()s. I bet Javascript got resumed at some arbitrary time before fully sleeping.)

I tested on Android 2.2 and the latest iOS - they both alert as soon as you resume from sleep.

ios - What happens to JavaScript execution (settimeout, etc.) when iPh...

android ios web-applications mobile settimeout
Rectangle 27 1

You can approach your situation in two ways.

This second option using a more general purpose utility function would look like this:

runIteration(function(i) {
    console.log(i);
}, 10, 1000);

This could also be extended with a 2nd callback function that was called when the iteration was complete (useful in some circumstances) or it could return a promise that is resolved when the iterations are complete.

Here's what a version that returns a promise would look like: http://jsfiddle.net/jfriend00/XtJ69/

// utility function to call a callback numTimes, 
// separated by delay milliseconds
function runIteration(fn, numTimes, delay) {
    var d = $.Deferred();
    var cnt = 0;

    function end() {
        d.resolve();
    }

    function next() {
        // call the callback and stop iterating if
        // it returns false
        if (fn(cnt) === false) {
            end();
            return;
        }
        ++cnt;
        // if not finished with desired number of iterations,
        // schedule the next iteration
        if (cnt < numTimes) {
            setTimeout(next, delay);
        } else {
            end();
        }
    }
    // start first iteration
    next();
    return d.promise();
}


runIteration(function(i) {
    log(i);
}, 10, 1000).done(function() {
    log("done");
});

settimeout - JavaScript : For loop with timeout - Stack Overflow

javascript settimeout
Rectangle 27 1

for (var i=0;i<=10;i++) {
   (function(ind) {
       setTimeout(function(){console.log((ind + 1)*1000, ':', ind);}, 1000 * (ind+1) );
   })(i);
}
1000 : 0
2000 : 1
3000 : 2
4000 : 3
5000 : 4
6000 : 5
7000 : 6
8000 : 7
9000 : 8
10000 : 9
11000 : 10

settimeout - JavaScript : For loop with timeout - Stack Overflow

javascript settimeout
Rectangle 27 15

Why function queueing in the first place?

setTimeout

Javascript engine is a single threaded process. So whenever developers wanted to defer some function execution to get executed right after the current one that's just being executed, a setTimeout is being used to actually queue the next function... It doesn't have anything to do directly with events although functions may be event handlers. The only event in this equation is the timeout event that setTimeout creates.

This is an example of two functions where the first function during its execution queues a second function to be executed right after it.

function first()
{
    // does whatever it needs to

    // something else needs to be executed right afterwards
    setTimeout(second, 1);

    // do some final processing and exit
    return;
}

function second()
{
    // whatever needs to be done
}
first()
second()

1ms is a very short amount of time, which (almost) assures that your second function will get executed right after your first function returns. You may see sometimes even 0ms which actually executes it right after first function returns.

If one would on the other hand use longer time i.e. 100ms this could result in a different function getting executed in the meantime and that could have an undesired effect on the whole UI process.

Browsers nowadays prevent client side functionality to hang current browser session by observing long running functions. If a particular function runs long enough, browser Javascript execution engine will pause it and ask the user whether they want to terminate it (kill it) or wait for it to complete.

This is usually undesired effect when you actually do have a long running function. For instance imagine you have a function that has to loop through a large number of items processing each one during the process. You definitely don't want the user to terminate the process because the loop needs to execute.

What's the solution in this case? In such case instead of having a single function with loop and executing it, you'd rather have the loop (queueing) function that would then queue function calls for processing each item. This is just an outer skeleton of such functionality.

function queueItems(items) {
    for(var i = 0; i < items.length, i++)
    {
        setTimeout((function(item) {
            return function() {
                processItem(item);
            };
        })(items[i]), 0);
    }
}

function processItem(item) {
    // process individual item
}

This way you'd prevent your functions to run too long and after each executed function control would get back to Javascript engine resetting its function-hang timer. But be aware that while your functions are being executed your UI will likely be unresponsive or at most unpredictable. It may be better to queue your function with some time space in between so UI stays responsive if that's desired.

jquery - Why are some JavaScript developers using setTimeout for one m...

javascript jquery settimeout tablesorter