定时器函数setTimeout 和 setInterval

定时器函数支持我们在几秒后再来运行代码;

setTimeout(() => console.log('三秒之后我才会出现'), 3000);  //会接受一个回调函数,第二个参数是设定的毫秒时间

在这里插入图片描述

● 在回调函数中也可以传入参数

setTimeout(
  (ex1, ex2) => {
    console.log(`馒头是由${ex1}${ex2}组成的`);
  },
  3000,
  '面粉',
  '水'
);

在这里插入图片描述

● 定时器是JavaScript异步函数的一种,它并不是影响后面代码的执行

setTimeout(
  (ex1, ex2) => {
    console.log(`馒头是由${ex1}${ex2}组成的`);
  },
  3000,
  '面粉',
  '水'
);

console.log('上面不会影响我执行的哦');

在这里插入图片描述

● 清除定时器

const ingredients = ['olives', 'spinach'];
const pizzaTimer = setTimeout(
  (ing1, ing2) => console.log(`Here is your pizza with ${ing1} and ${ing2}`),
  3000,
  ...ingredients
);

if (ingredients.includes('spinach')) clearTimeout(pizzaTimer);

//
这段代码设置了一个定时器来模拟制作披萨的时间。如果菠菜是其中一种配料,它会在定时器到期之前清除定时器,表示披萨已经准备好了。

实例

现在我们将我们学习的知识运用到实际的项目中,我们在申请贷款的时候一般是需要时间的,我们将我们的应用程序添加一个这样的功能吧

btnLoan.addEventListener('click', function (e) {
  e.preventDefault();

  const amount = Math.floor(inputLoanAmount.value);

  if (amount > 0 && currentAccount.movements.some(mov => mov >= amount * 0.1)) {
    // Add movement
    setTimeout(function () {
      currentAccount.movements.push(amount);

      currentAccount.movementsDates.push(new Date().toISOString());

      // Update UI
      updateUI(currentAccount);
    }, 3000);
  }
  inputLoanAmount.value = '';
});

setTimeout只会将函数执行一遍,下面我们学习将函数运行设置时间间隔;

setInterval
setInterval(() => {
  const time = new Date();
  console.log(time);
}, 1000);

在这里插入图片描述

下一篇我们将上面所学习的知识完全应用到我们的应用程序上面去;

  • 6
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值