I am a beginner with Javascript.

Why won't c go up every time popup() is called?

I used document.write to see if it would go up but it stays with 1.

<script>

    var c = 0;



window.onload=function()
{
    var myVar = setInterval('popup()',2000);

    c++;
    document.write(c);
    if(c>2)
    {
    clearInterval(myVar);
    }
}

function popup()
{
    alert('hallo');

}

</script>

Code where interval won't stop after c>2.

<script>

var c = 0;
var myVar = null;

window.onload=function()
{
    myVar = setInterval('popup()',2000);
}

function popup()
{
    alert('hallo');
    c++;
    document.write(c);
    if(c>2)
    {
        clearInterval(myVar);
    }
}

</script>
有帮助吗?

解决方案

At loading of your page, you call setInterval.

So, every two seconds, you will call the popup function, which says 'hallo'.

Then, you increment your variable, etc...

=> To get your c variable incremented, increment it in the popup function.

EDIT: To answer the comment with a better layout:

setInterval() returns an interval ID, which you can pass to clearInterval():

var refreshIntervalId = setInterval(fname, 10000);

/* later */

clearInterval(refreshIntervalId);

其他提示

You need to raise c in your function:

function popup()
{
    alert('hallo');
    c++;
}

At window.onload, you are calling setInternal method in which you are calling popup function. So you need increment and print cin popup function. Also, clearInterval needs to be called in popup function as well.

<script>
    var c = 0,
        myVar;
    window.onload = function () {
        myVar = setInterval(popup, 2000);
    }

    function popup() {
        //alert('hello');
        c++;
        document.write(c);
        if (c > 2) {
            clearInterval(myVar);
        }
    }
</script>

JSFiddle: http://jsfiddle.net/jaNjn/

Your window.onload function is called only once when page loads. You must increment a check c in your popup function

var c = 0;
var myVar = null;

window.onload=function()
{
    myVar = setInterval('popup()',2000);
}

function popup()
{
    alert('hallo');
    c++;
    document.write(c);
    if(c>2)
    {
        clearInterval(myVar);
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top