睡在javascript for循环中

时间:2016-12-23 08:23:28

标签: javascript loops for-loop sleep

我试图创建一个每1秒更新一次的计数器。我做了一个后端函数,每30秒返回一次,用Ajax调用。呼叫的结果除以30,然后应每隔1秒更新一次计数器30秒。我怎样才能在for-loop中进行睡眠?

到目前为止,这是我的代码:

function getCount() {
    $.ajax({
        url: '@Url.Action("", "", new {area = ""})',
        type: 'POST',
        success: function (data) {
            var newTotalCount = data.totalCount;
            var newDanishCount = data.danishCount;
            var newNorwayCount = data.norwayCount;
            var newSwedenCount = data.swedenCount;
            var newUsCount = data.usCount;

            var currentTotalCount = $("#odoTotal").text().replace(/,/g, "").replace(/(\r\n|\n|\r)/gm, "");
            var currentDanishCount = $("#odoDk").text().replace(/,/g, "").replace(/(\r\n|\n|\r)/gm, "");
            var currentNorwayCount = $("#odoNo").text().replace(/,/g, "").replace(/(\r\n|\n|\r)/gm, "");
            var currentSwedenCount = $("#odoSe").text().replace(/,/g, "").replace(/(\r\n|\n|\r)/gm, "");
            var currentUsCount = $("#odoUs").text().replace(/,/g, "").replace(/(\r\n|\n|\r)/gm, "");

            var updateTotalCount = newTotalCount - currentTotalCount;
            var updateDanishCount = newDanishCount - currentDanishCount;
            var updateNorwayCount = newNorwayCount - currentNorwayCount;
            var updateSwedenCount = newSwedenCount - currentSwedenCount;
            var updateUsCount = newUsCount - currentUsCount;

            var updateTotalPerSecond = updateTotalCount / 30;
            var updateDanishPerSecond = updateDanishCount / 30;
            var updateNorwayPerSecond = updateNorwayCount / 30;
            var updateSwedenPerSecond = updateSwedenCount / 30;
            var updateUsPerSecond = updateUsCount / 30;


            getAllSales();

            for (var i = 0; i < 30; i++) {
                window.setTimeout(function() {
                    $("#odoTotal").html(currentTotalCount+updateTotalPerSecond);

                    $("#odoDk").html(currentDanishCount+updateDanishPerSecond);

                    $("#odoNo").html(currentNorwayCount+updateNorwayPerSecond);

                    $("#odoSe").html(currentSwedenCount+updateSwedenPerSecond);

                    $("#odoUs").html(currentUsCount+updateUsPerSecond);

                    currentTotalCount = $("#odoTotal").text().replace(/,/g, "").replace(/(\r\n|\n|\r)/gm, "");
                    currentDanishCount = $("#odoDk").text().replace(/,/g, "").replace(/(\r\n|\n|\r)/gm, "");
                    currentNorwayCount = $("#odoNo").text().replace(/,/g, "").replace(/(\r\n|\n|\r)/gm, "");
                    currentSwedenCount = $("#odoSe").text().replace(/,/g, "").replace(/(\r\n|\n|\r)/gm, "");
                    currentUsCount = $("#odoUs").text().replace(/,/g, "").replace(/(\r\n|\n|\r)/gm, "");


                }, 1000);

            }

        }
    });

}

2 个答案:

答案 0 :(得分:2)

我得到了一个解决方案

首先创建一个你将要增加的变量

class ToDoTableViewController: UITableViewController {    

  var listItems = [NSManagedObject]()

  override func viewDidLoad() {
    super.viewDidLoad()

    self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.add, target: self , action: #selector(ToDoTableViewController.addItem))

    navigationController?.navigationBar.barTintColor = UIColor(red: 220/255, green: 26/255, blue: 104/255, alpha: 1)
    tableView.backgroundView = UIImageView(image: UIImage(named: "settingsscreen.png"))

  }

// for adding items

  func addItem(){

    let alertController = UIAlertController(title: "To Do Tasks Lists!!!!", message: "Write Down...", preferredStyle: .alert)

    let confirmAction = UIAlertAction(title: "Confirm", style: UIAlertActionStyle.default, handler: ({
        (_) in

        if let field = alertController.textFields![0] as? UITextField {

            self.saveItem(itemToSave: (field.text!))
            self.tableView.reloadData()

        }
        }                        
    ))

    // for cancel alert controller

    let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil)

    alertController.addTextField(configurationHandler: ({
        (textField) in

        textField.placeholder = "Type in Something!!!!"
    }))

    alertController.addAction(confirmAction)
    alertController.addAction(cancelAction)

    self.present(alertController, animated: true, completion: nil)                
  }

  // to save the data on core data

  func saveItem(itemToSave : String){

    let appDelegate = UIApplication.shared.delegate as! AppDelegate

    let managedContext = appDelegate.managedObjectContext

    let entity = NSEntityDescription.entity(forEntityName: "ListEntity", in: managedContext)

    let item = NSManagedObject(entity: entity!, insertInto: managedContext)

    item.setValue(itemToSave, forKey: "item")

    do {
        try managedContext.save()
        listItems.append(item)
    }
    catch {

        print("Error")
    }                                
  }

  // to show the existing data on core data 

  override func viewWillAppear(_ animated: Bool) {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate

    let managedContext = appDelegate.managedObjectContext

    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "ListEntity")

    do{
        let results = try managedContext.fetch(fetchRequest)

        listItems = results as! [NSManagedObject]
    }
    catch {
        print("Error")
    }                
  }

  override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true

  }

  override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        listItems.remove(at: indexPath.row)
        tableView.reloadData()
    }               
  }

  override func setEditing(_ editing: Bool, animated: Bool) {
    super.setEditing(editing, animated: animated)
    tableView.reloadData()
  }

  override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return listItems.count
  }

  override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")! as UITableViewCell

    let item = listItems[indexPath.row]

    cell.textLabel?.text = item.value(forKey: "item") as! String?

    cell.backgroundColor = UIColor.clear
    return cell
  }
}

然后创建一个间隔,它会在例如5(s)的时间结束后执行您想要的操作,这也会在每次运行时增加值var x = 0;

x

示例函数

var interval = setInterval(function() {
    if (x >= 5) { // just change 5 to 30
        console.log('Loop timeout ended');
        return clearInterval(interval);
    }
    // do what ever you want
    console.log('Current x: '+x);
    x++;
}, 5000); 

Demo

答案 1 :(得分:0)

如果您使用的是Firefox 53+或babel,则可以使用ES2017:

async function promiseTimeout(milliseconds) {
    await new Promise(resolve => setTimeout(()=>resolve(), milliseconds))
}

async function countDown(from) {
    while (from) {
        console.log(from--, 'seconds left');
        await promiseTimeout(1000);
    }
    alert('countdown done');
}

countDown(10);

Here与babel有关。