范围上的优化,window.setInterval或.change函数

时间:2018-02-24 08:12:33

标签: javascript input range setinterval

我有点想到50ms的setInterval函数不好?或者我错了......所以这是这里的情况,我有一个输入范围,我希望在变化时得到该范围的值..所以我有这两个代码..

$('#transparency-range').change(function(){
   $(".transparency-color span").text($('#transparency-range').val() + "%")
 })

//第二代码

window.setInterval(function(){
  $(".transparency-color span").text($('#transparency-range').val() + "%")
}, 50);

第一个代码可能更适合优化吗? 第一个代码的问题是我没有获得有价值的实时信息,所以在我的文本字段中我想显示该信息,数字只有在我完成更改后才会更改, 使用第二个代码时,我正在改变数字,而我正在移动范围输入..

我在应用程序中使用类似的代码超过10次,这就是为什么这个优化问题有点重要:)

谢谢!

2 个答案:

答案 0 :(得分:0)

如果您立即收听import java.awt.*; import java.awt.event.*; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.WritableRaster; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Random; import javax.imageio.ImageIO; import javax.swing.*; import javax.swing.filechooser.FileNameExtensionFilter; @SuppressWarnings("serial") public class FromGraphicsToBufferedImage extends JPanel{ private static final int BI_WIDTH = 600; private static final int BI_HEIGHT = BI_WIDTH; private static BufferedImage bImage = new BufferedImage(BI_WIDTH, BI_HEIGHT, BufferedImage.TYPE_INT_ARGB); //Enregistrement de l'image en RGBA private List<Point> pointList = new ArrayList<Point>(); private JLabel imageLabel; private boolean isInit = false; private static ArrayList<BufferedImage> historic = new ArrayList<BufferedImage>(); private int historicIndex = 0; //Constructeur public FromGraphicsToBufferedImage() { imageLabel = new JLabel(new ImageIcon(bImage)) { @Override protected void paintComponent(Graphics g) { super.paintComponent(g); paintInLabel(g); } }; MyMouseAdapter myMouseAdapter = new MyMouseAdapter(); imageLabel.addMouseListener(myMouseAdapter); imageLabel.addMouseMotionListener(myMouseAdapter); imageLabel.setBorder(BorderFactory.createEtchedBorder()); JButton saveImageBtn = new JButton("Save Image"); saveImageBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { saveImageActionPerformed(); } }); JButton clearImageBtn = new JButton("Clear Image"); clearImageBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Graphics2D g2 = bImage.createGraphics(); g2.setBackground(new Color(255,255,255,0)); g2.clearRect(0, 0, BI_WIDTH, BI_HEIGHT); g2.dispose(); imageLabel.repaint(); } }); JButton undo = new JButton("Undo"); undo.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.println("UNDO"); historicIndex -= 1; bImage = historic.get(historicIndex); Graphics2D g2 = bImage.createGraphics(); g2.drawImage(bImage, 0, 0, bImage.getWidth(), bImage.getHeight(), imageLabel); g2.dispose(); imageLabel.setIcon(new ImageIcon(bImage)); imageLabel.repaint(); } }); JPanel btnPanel = new JPanel(); btnPanel.add(saveImageBtn); btnPanel.add(clearImageBtn); btnPanel.add(undo); setLayout(new BorderLayout()); add(imageLabel, BorderLayout.CENTER); add(btnPanel, BorderLayout.SOUTH); } //Fin du Constructeur private void saveImageActionPerformed() { JFileChooser filechooser = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter("PNG Images", "png"); filechooser.setFileFilter(filter); int result = filechooser.showSaveDialog(this); if (result == JFileChooser.APPROVE_OPTION) { File saveFile = filechooser.getSelectedFile(); try { ImageIO.write(bImage, "png", saveFile); } catch (IOException e) { e.printStackTrace(); } } } private void paintInLabel(Graphics g) { Graphics2D g2d = (Graphics2D) g; g2d = bImage.createGraphics(); if(isInit == false) { g2d.setColor(Color.RED); g2d.fillRect(0, 0, BI_WIDTH, BI_HEIGHT); g2d.dispose(); isInit = true; } else { g2d.setColor(Color.BLUE); if(pointList.size() == 0) { return; } //System.out.println(bImage.getRGB(50, 50)); int x1 = pointList.get(0).x; int y1 = pointList.get(0).y; int x2 = pointList.get(0).x+32; int y2 = pointList.get(0).y+32; g2d.setComposite(AlphaComposite.Src); g2d.setColor(new Color(255,255,255,0)); g2d.fillRect(x1,y1,32,32); g2d.dispose(); pointList.clear(); } historic.add(deepCopy(bImage)); imageLabel.repaint(); } private class MyMouseAdapter extends MouseAdapter { @Override public void mousePressed(MouseEvent e) { pointList.add(e.getPoint()); imageLabel.repaint(); } @Override public void mouseReleased(MouseEvent e) { //historic.add(deepCopy(bImage)); System.out.println("Historic Size: " + historic.size()); int tailleHistorique = historic.size(); historicIndex = tailleHistorique-1; if(historic.size() >= 2) { System.out.println("The 2 images are the same: " + compareImages(historic.get(historicIndex-1), historic.get(historicIndex))); } } } private static void createAndShowUI() { JFrame frame = new JFrame("DrawAndSaveImage"); frame.getContentPane().add(new FromGraphicsToBufferedImage()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } public static BufferedImage getBufferedImage() { return bImage; } public static boolean compareImages(BufferedImage imgA, BufferedImage imgB) { if (imgA.getWidth() == imgB.getWidth() && imgA.getHeight() == imgB.getHeight()) { int largeurImage = imgA.getWidth(); int hauteurImage = imgA.getHeight(); for (int y = 0; y < hauteurImage; y++) { for (int x = 0; x < largeurImage; x++) { if (imgA.getRGB(x, y) != imgB.getRGB(x, y)){ return false; } } } } else { return false; } return true; } static BufferedImage deepCopy(BufferedImage bi) { ColorModel cm = bi.getColorModel(); boolean isAlphaPremultiplied = cm.isAlphaPremultiplied(); WritableRaster raster = bi.copyData(null); return new BufferedImage(cm, raster, isAlphaPremultiplied, null); } public static void main(String[] args) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { createAndShowUI(); } }); } } 事件(每次更改都会触发),您可能会获得更好的结果:

input

如果这样做,那么它肯定比使用计时器更好。

答案 1 :(得分:0)

  1. setInterval是跟踪输入更改的不错选择,因为它不会与输入中的实际更改同步,它会依靠自己的生命,而且非常重要的是需要使用{{1}进行清理}和clogs事件循环使用不必要的执行,从而使你的整个应用程序更慢。

  2. 更好的方法是倾听输入的特定事件,例如clearIntervalchangeinputkeyupkeypress。它们是专门为处理此类案件而设计的,这就是为什么它们有各种各样的原因。

  3. 因此,如果我们选择keydown,它将如下所示:

    input

    在您键入每个字符后,这将为您提供即时更改反馈。

    1. 这仍然无法让您免于清除事件监听器,但至少现在您的事件监听器专门跟踪输入更改而不仅仅是间隔执行。
    2. 你可以这样做:

      $('#transparency-range').on('input', function(){
         $(".transparency-color span").text($(this).val() + "%");
      });

      1. 最后但并非最不重要,因为你的问题是关于优化, 有debouncing函数调用的这种做法,在你的情况下会给你最好的两个世界,你仍然会有延迟执行,你可以控制,但现在它会发生在你输入​​而不是模糊。
      2. 使用上述插件,如果您需要在用户停止输入后的250ms内执行您的功能,可以使用以下内容:

        function inputHandler() {
          $(".transparency-color span").text($(this).val() + "%");
        }
        
        $('#transparency-range').on('input', inputHandler);
        
        //...
        // later in you code when needed
        $('#transparency-range').off('input', inputHandler);