简体   繁体   English

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

[英]Can setInterval store a value in a variable

Look at this code 看这段代码

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')
}

How come the if statement does not execute when count2 = 5 为什么在count2 = 5时if语句不执行

The problem is: First you only define the logic for the interval and then you check the count2 variable. 问题是:首先,您只定义间隔的逻辑,然后检查count2变量。 But in that context the variable has still the value 0. 但是在这种情况下,变量的值仍为0。

Each time the interval is fired (and in most cases it is after the if-check), only the part inside the function() { } block is executed 每次触发间隔时(大多数情况下是在if-check之后),仅执行function(){}块内的部分

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

and it is not continued to the if statement because it is not part of the interval logic. 并且它不会继续到if语句,因为它不是区间逻辑的一部分。

The first idea I have is to put the if statement into the function() { } block like this: 我的第一个想法是将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);
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')
}

Read a tutorial to get started: https://developer.mozilla.org/en/JavaScript/Guide . 阅读入门指南: https : //developer.mozilla.org/en/JavaScript/Guide

yes it can store a value. 是的它可以存储一个值。

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

Try This Out, it works 试试看,它有效

//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) ;} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM