user1801625
user1801625

Reputation: 1223

Callback function in javascript

What is the problem with this code

var a=function()
{
   setInterval(function(){document.write("a");},1000);
}

function b(callback)
{
    callback();
    alert(2);
}

b(a); // alert 2

It should not not show me the alert because the call not over yet?

Upvotes: 0

Views: 571

Answers (2)

StuR
StuR

Reputation: 12218

You could add the callback into your setInterval function so that it doesn't get executed until after the 1000 millisecond delay, e.g:

    var a=function(callback) {
        setInterval(function(){document.write("a"); callback(); },1000);
    }

    function b() {
        alert(2);
    }

a(b); // alert 2 AFTER the 1000 millisecond delay

Upvotes: 1

Gurpreet Singh
Gurpreet Singh

Reputation: 21233

The code is running as expected. SetInterval doesn't hold the execution for rest of the code it fires assigned function after specified time.

So you will get alert and then document.write.

Upvotes: 1

Related Questions