0

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?

4
  • 1
    setInterval is asynchronous. It schedules the execution of the function, but returns immediately. Commented Nov 13, 2012 at 11:37
  • What was expected and what was the output? Commented Nov 13, 2012 at 11:37
  • Are you sure you are not getting the alert? Commented Nov 13, 2012 at 11:37
  • I get the alert but I learn that callback its first do the setInteval and after that thae alert or that I'm wrong? Commented Nov 13, 2012 at 11:38

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

so what is the use of callback?
As I mentioned before it will be fired after '1000' ms
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.