对涉及 setTimeout() 方法的 JavaScript 代码帮助不大 [英] Little help with JavaScript code involving setTimeout() method

查看:51
本文介绍了对涉及 setTimeout() 方法的 JavaScript 代码帮助不大的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解这段代码的两件事:

I am trying to understand two things about this code:

var updateFn = function(num){
   return function(){
      if(num == 6){
         console.info("100%, all items saved!")
      }
      else{
         var i = num/6;
         var pct = Math.round(100 * i);
         console.info(pct + "% saved");
      }
  };
};

for (var i = 1; i < 7; i++){
   setTimeout(updateFn(i), i * 500);
}

  1. 根据我对 setTimeout() 语法的了解;

  1. According to what i have read about setTimeout() syntax;

setTimeout("javascriptstatement",milliseconds);

那么,为什么我必须增加每个循环的毫秒数,直到总时间达到 500*6 毫秒?为什么 setTimeout(updateFn(i), 500); 不能按预期工作?

So, why do I have to increment the milliseconds each loop till the total time until 500*6 ms? Why doesn't setTimeout(updateFn(i), 500); work as intended?

为什么我必须为作为第一个参数传递的函数返回一个函数设置超时?

Why do I have to return a function for the function passed as the first parameter of setTimeout?

为什么这不起作用?:

var updateFn = function(num){
      if(num == 6){
         console.info("100%, all items saved!")
      }
      else{
         var i = num/6;
         var pct = Math.round(100 * i);
         console.info(pct + "% saved");
      }

};

for (var i = 1; i < 7; i++){
   setTimeout("updateFn(i)", i * 500);
}

提前致谢.

推荐答案

  1. 似乎每 500 毫秒设置 6 次超时.我认为 setInterval 在这里可能会更好.

您想要返回一个函数,因为如果您将字符串传递给 setTimeout,它会得到 eval ed,如果您传递一个函数,它只会运行它.

You want to return a function because if you pass a string to setTimeout it gets evaled, and if you pass a function it just runs it.

似乎这段代码正在为保存操作制作一个进度表,尽管假设保存需要 3 秒,并且每 1/2 秒增加一次计数器可能不是最好的主意.

It seems this code is making a progress meter for a save operation, though assuming the save will take 3 seconds, and incrementing the counter every 1/2 second may not be the best idea.

无论如何,与其设置6个超时,不如使用setInterval.

Anyway, instead of setting 6 timeouts, it would be better to use setInterval.

var updateFn = function(num){
  if(num == 6){
     console.info("100%, all items saved!");
     clearInterval(saving);
  }
  else{
     var i = num/6;
     var pct = Math.round(100 * i);
     console.info(pct + "% saved");
  }
};

var count = 1
var saving = setInterval(function(){
    updateFn(count++);
}, 500);

这篇关于对涉及 setTimeout() 方法的 JavaScript 代码帮助不大的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆