I was playing around with callbacks and ran into this problem, unsure how related it is to callbacks, but I cant explain the result, any help would be greatly appreciated.
Why is the result: 'hi samsamsamsamsamsamsamsamsamsamsamsam',
I would expect: 'hi sam'
function addSam(cb){
var name = '';
setTimeout(function(){
name += 'sam';
cb();
}, 1000);
}
function speak(){
console.log('hi ' + name);
}
When I call addSam(speak),
The console returns:
'hi samsamsamsamsamsamsamsamsamsamsamsam'
Why does name += 'sam' happen multiple times?
How should I change the code so this only happens once and I can output simply:
hi sam
"hi". I am damn surevar name = '';in your real code.