Reputation: 1719
I am using the below mentioned code to call a function(addCard) ,which adds images to the web page. The browser freezes due to this. If I call a simple function which does not update UI in setTimeOut, then the browser does not freeze. So, can't we update UI in the setTimeOut callback function. As far as I know, the javascript runtime for browser is single threaded. So, there is no separate UI thread. Then why is the browser freezing? As the callback will be run in the main thread. Here is the code:
while(user.Score > dealer.Score){
setTimeout(function(){addCard(dealer);},2000);
}
Upvotes: 1
Views: 637
Reputation: 612
The simple explanation for the browser to freeze is the browser running out of resources.
Since the addCard(dealer)
function works when outside the setTimeout(), it leads me to believe the implementation with the timeout is the cause. The most obvious one being that the UI update is taking longer to complete than the time available to the thread. And since the while loop will keep executing, eventually the call stack will fill up. This will also explain why the browser freezes without throwing any errors.
You should be able to confirm this behavior by debugging the code. I would however recommend you modify the logic rather then trying a workaround to the issue.
Upvotes: 2
Reputation: 6336
Your got stuck in infinity loop, since user.Score > dealer.Score
will never be false. Also, you get recursion since you call the same function each 2 seconds, that creates recursion by itself. The browser, low out of memory, get stuck.
Upvotes: 2