setInterval可以在变量中存储一个值

时间:2010-12-26 04:46:21

标签: javascript setinterval

看看这段代码

var count = 0, count2 = 0
setInterval(function() {
    // I wrote this on two lines for clarity.
    ++count;
    count2 = count;
}, 1000);
if(count2==5)
{
alert('testing script')
}

为什么if语句在count2 = 5时不执行

4 个答案:

答案 0 :(得分:1)

问题是:首先,您只定义间隔的逻辑,然后检查count2变量。但在该上下文中,变量的值仍为0。

每次触发间隔(并且在大多数情况下它是在if-check之后),只执行function(){}块内的部分

function() {
    // I wrote this on two lines for clarity.
    ++count;
    count2 = count;
}

并且不会继续if语句,因为它不是区间逻辑的一部分。

我的第一个想法是将if语句放入function(){}块中,如下所示:

var count = 0, count2 = 0;

setInterval(function() {

    // I wrote this on two lines for clarity.
    ++count;
    count2 = count;

    if(count2 == 5)
    {
        alert('testing script');
    }

}, 1000);

答案 1 :(得分:1)

var count = 0, count2 = 0 // missing semi colon(!)
setInterval(function() { // this function will be executed every 1000 milliseconds, if something else is running at that moment it gets queued up
    ++count; // pre-increment count
    count2 = count; // assign count to count 2
}, 1000);

// ok guess what this runs IMMEDIATELY after the above, and it only runs ONCE so count 2 is still 0
if(count2==5) // DON'T put { on the next line in JS, automatic semi colon insertion will get you at some point
{
    alert('testing script')
}

阅读教程以开始使用:https://developer.mozilla.org/en/JavaScript/Guide

答案 2 :(得分:0)

是的,它可以存储一个值。

function hello(){
    var count = 0;
    var timer = setInterval( function(){  count+=1;alert(count); },2000);
}

答案 3 :(得分:0)

试一试,它有效

//Counting By Z M Y.js
if(timer){window.clearInterval(timer)} /*← this code was taped , in order to avoid a sort of bug , i'm not going to mention details about it  */
c=0; 
do{   w=prompt('precise the number of repetition in which the counting becomes annoying',10)} 

                                    while (!(w>0)||w%1!=0)
   function Controling_The_Counting(c,w)
   {
if(c%w==0&&c>0){return confirm('do you want to continue ?'); }
return true;
   } 

    var timer = setInterval( function(){  console.clear();c+=1;console.log(c); StopTimer()  },1000);
  function StopTimer() {  if(!Controling_The_Counting(c,w)) {window.clearInterval(timer) ;} }