Может setInterval сохранить значение в переменной - PullRequest
0 голосов
/ 26 декабря 2010

Посмотрите на этот код

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 ]

1 голос
/ 26 декабря 2010
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.

1 голос
/ 26 декабря 2010

Проблема: сначала вы определяете логику для интервала, а затем проверяете переменную count2. Но в этом контексте переменная по-прежнему имеет значение 0.

Каждый раз, когда запускается интервал (и в большинстве случаев он идет после проверки if), выполняется только часть внутри блока 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);
0 голосов
/ 06 сентября 2014

Попробуйте, все работает

//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) ;} }
0 голосов
/ 13 ноября 2012

да, он может хранить значение.

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