Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A simple example demonstrating how setTimeout(fn, 0) can be useful. This gist illustrates the answer given by DVK's on stackoverflow. http://stackoverflow.com/a/4575011/783478
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<button id='do'> Do long calc!</button>
<div id='status'></div>
<div id='result'></div>
<script>
$('#do').on('click', function(){
$('#status').text('calculating....')
// without set timeout, user will never see "calculating...."
long()
// with set timeout, works as expected
//setTimeout(long,0)
})
function long(){
var result = 0
for (var i = 0; i<1000; i++){
for (var j = 0; j<1000; j++){
for (var k = 0; k<1000; k++){
result = result + i+j+k
}
}
}
$('#status').text('calclation done') // has to be in here for this example. or else it will ALWAYS run instantly. This is the same as passing it a callback
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.