javascript – 重复JS功能

前端之家收集整理的这篇文章主要介绍了javascript – 重复JS功能前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我试图让这个函数在它的循环结束时重复.我尝试将函数分配给变量并在回调中调用变量,但是失败了.我尝试在setInterval函数中包装此函数,仍然无法使其工作.

如何使此函数运行无限循环并重复自身?

$("span.text-change").typed({
     strings: ["First sentence.","Second sentence."],typeSpeed: 30,// typing speed
     backDelay: 500,// pause before backspacing
     callback: function () {
         // do stuff
     }
 });

这是插件
Typed JS

jsFiddle here

最佳答案
代码放在一个区间是个好主意.但是,您必须在再次调用之前检查代码执行是否已完成.您可以使用用作标志的布尔变量来完成此操作.

var timerId = setInterval(function() {
    flag=true;
 if( flag){
     flag=false;
    $("div").typed({
     strings: ["First sentence.",// pause before backspacing
     callback: function () {
         flag=true;
         //destroy typed plugin here. See in the api if 
         //there is a method for doing that.

     }
 });

 }

},1000);

当你不想停止循环时,你可以简单地摧毁计时器

clearInterval(timerId);

edit: I’ve added an option to the plugin

$("#typed").typed({
    strings: ["Typed.js is a jQuery plugin.","It types out sentences."],backDelay: 500,loop:true,callback: function(){ alert('end'); }
});

编辑过的插件文件

!function($){

    "use strict";

    var Typed = function(el,options){

        // for variable scope's sake
        self = this;

        // chosen element to manipulate text
        self.el = $(el);
        // options
        self.options = $.extend({},$.fn.typed.defaults,options);

        // text content of element
        self.text = self.el.text();

        // typing speed
        self.typeSpeed = self.options.typeSpeed;

        // typing speed
        self.loop = self.options.loop;

        // amount of time to wait before backspacing
        self.backDelay = self.options.backDelay;

        // input strings of text
        self.strings = self.options.strings;

        // character number position of current string
        self.strPos = 0;

        // current array position
        self.arrayPos = 0;

        // current string based on current values[] array position 
        self.string = self.strings[self.arrayPos];

        // number to stop backspacing on.
        // default 0,can change depending on how many chars
        // you want to remove at the time
        self.stopNum = 0;

        // number in which to stop going through array
        // set to strings[] array (length - 1) to stop deleting after last string is typed
        self.stopArray = self.strings.length-1;

        // All systems go!
        self.init();
    }

        Typed.prototype =  {

            constructor: Typed,init: function(){
                // begin the loop w/ first current string (global self.string)
                // current string will be passed as an argument each time after this
                self.typewrite(self.string,self.strPos);
                self.el.after("

猜你在找的jQuery相关文章