javascript - Angular $timeout 延迟

标签 javascript angularjs

我希望浏览器在执行下一行代码之前等待 3 秒。

$超时(3000);在脚本中似乎没有奏效。我在这里做错什么了吗。

我在 $scope 函数中使用它

app.expandController = function ($scope,$interval, $timeout) {

    $scope.nextLevel = function () {

            //stop numbers
            $scope.StopTimer();

            $timeout(function(){return true;},3000);

            //restart timer with new numbers
            $scope.StartTimer();

            $scope.thresholdwatch == false
        }
}

我通过将 $scope 和 $timeout 传递给另一个函数来拆分 Controller 文件
app.controller('myCtrl', function ($scope, $interval, $timeout) {


    app.expandController($scope, $interval,$timeout);

});

最佳答案

如果您使用 $timeout您需要将下一个执行代码放在超时回调中。但是用 vanila js 做一个简单的 hack 就是,

function sleep(ms) {
  var dt = new Date();
  while (Date.now() - dt.getTime() <= ms) {}
  return true;
}

console.log('timer start');
sleep(3000);
console.log('Printing after 3000ms');

关于javascript - Angular $timeout 延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42990764/

相关文章:

javascript - 我正在尝试编写 js 代码以使用 onmouseover 事件在 div 中显示图像

javascript - Angular——如何使资源全局化?

css - 如何将不同的类传递给元素指令

javascript - 标签过去最后一个单元格时自动在 ng-grid 中添加行

javascript - IE6 的 Textarea 问题 - 我正在使用 javascript 的 Jquery 框架

javascript - 使用setInterval更新按钮上的文本

javascript - 如何根据窗口名称切换 anchor 目标

angularjs - 在angularjs中的每个 View 加载上创建与socket.io的新连接

javascript - SAP UI5 与其他 Javascript 框架的对比?

javascript - 在此特定示例中如何将 Javascript 变量传递给 Twig